Reputation: 5605
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 there are more simpler ways of checking if a textbox has a numeric value.
var query = $('#myText').val();
if (parseFloat(query) == NaN) {
alert("query is a string");
} else {
alert("query is numeric");
}
Upvotes: 8
Views: 33243
Reputation: 87233
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:
If you want to allow only numbers, you can use input-number
and pattern
<input type="number" pattern="\d+" />
Upvotes: 27
Reputation: 2423
Jquery provides generic util method to handle this. handles numeric/float/hex
$.isNumeric( value )
Try: fiddle
Upvotes: 2
Reputation: 8204
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">
Upvotes: 4
Reputation: 3015
There're many ways, you can use isNaN
isNaN(VALUE);
You can also use regEx to verify numeric values.
console.log(/^\d+$/.test(VALUE));
Upvotes: 2
Reputation: 367
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
}
Upvotes: 0