How to check if a textbox contains numbers only?
While googling I came across this. But I\'m wondering if isNumeric
can be used for this purpose or if t
There're many ways, you can use isNaN
isNaN(VALUE);
You can also use regEx to verify numeric values.
console.log(/^\d+$/.test(VALUE));
Jquery provides generic util method to handle this. handles numeric/float/hex
$.isNumeric( value )
Try: fiddle
You can check if the user has entered only numbers using change
event on input and regex.
$(document).ready(function() {
$('#myText').on('change', function() {
if (/^\d+$/.test($(this).val())) {
// Contain numbers only
} else {
// Contain other characters also
}
})
});
REGEX:
/
: Delimiters of regex^
: Starts with\d
: Any digit+
: One or more of the preceding characters$
: EndRegex Visualization:
Demo
If you want to allow only numbers, you can use input-number
and pattern
<input type="number" pattern="\d+" />
using pure JS regular expression
var query = document.getElementById('myText').value;
var isNumeric=query.match(/^\d+$/);
if(isNumeric){/*...*/}else{/*...*/}
or using html5 control
<input type="number" name="quantity" min="1" max="5">
You can match the value of text box against the numeric regression to check if it contains numbers only or not, Like below code...
if($('#myText').val().match(/^\d+$/)){
// Your code here
}