Dear Readers,
Sometimes we have need of validation in number type input
field in web pages. Main types of validations are :
1)
Drag and drop should be disabled
2)
Input should be only number whether on paste or
on input.
3)
Should allow only one dot in the input number if
input is decimal
Here, we will take input type=”number” control of HTML. You can
use type=”text” as well. Basic benefit of this control is, it provides basic
validations automatically. For more details about number type input, CLICKHERE.
Step 1: Create a
JS file in your editor, Notepad, Notepad++, Visual Studio Code etc.
Step 2: Write the
following code:
Following code will disable the Drag and Drop to the
control-
$(':input[type="number"]').attr("ondrop", "return false;");
$(':input[type="number"]').attr("ondrag", "return
false;");
Following code will
validate the value on keypress of the keyboard.
$(':input[type="number"]').keypress(function (event) {
// allow only one dot (.) in numeric field (For decimal
values)
// It will also restrict 'e' + - symbols for numeric text
boxes because these symbols can be entered by default in input type ‘number’
if(event.which
!= 8 && ((event.which != 46 || (event.which == 46 && $(this).val() == '')) ||
$(this).val().indexOf('.') != -1) &&
(event.which < 48 || event.which > 57)){
return false;
}
});
Step 3:
Write the following code for validation on paste of the values
$(':input[type="number"]').on('paste', function () {
var
ctrlval = $(this).val();
var
$this = $(this);
setTimeout(function () {
if
(!$.isNumeric($this.val())) {
$this.val($this.val().replace(/[^0-9]/g, ''));
$this.val(ctrlval);
}
}, 4);
});
Step 4:
Save the file with .JS extension and drag and drop link of this file in your
webpage.
For example: <script src="~/JS/CommonJS.js"></script>
I hope it will help. Mail me
for any more query. Suggestions/feedbacks are most welcome.
CLICK HERE to subscribe my
youtube channel.
Happy Coding.
Rudra Pratap Singh
Software Engineer
No comments:
Post a Comment