I have a simple textbox in which users enter number. Does jQuery have a isDigit function that will allow me to show an alert box if users enter something other than digits?
the field can have decimal points as well.
I have a simple textbox in which users enter number. Does jQuery have a isDigit function that will allow me to show an alert box if users enter something other than digits?
the field can have decimal points as well.
I would suggest using regexes:
var intRegex = /^\d+$/;
var floatRegex = /^((\d+(\.\d *)?)|((\d*\.)?\d+))$/;
var str = $('#myTextBox').val();
if(intRegex.test(str) || floatRegex.test(str)) {
alert('I am a number');
...
}
Or with a single regex as per @Platinum Azure's suggestion:
var numberRegex = /^[+-]?\d+(\.\d+)?([eE][+-]?\d+)?$/;
var str = $('#myTextBox').val();
if(numberRegex.test(str)) {
alert('I am a number');
...
}
jQuery is a set of JavaScript functions, right? So you could use JavaScript's regular expression support to validate the string. You can put this in a jQuery callback if you like, too, since those just take anonymously-declared function bodies and the functions are still JavaScript.
Value validation wouldn't be a responsibility of jQuery. You can use pure JavaScript for this. Two ways that come to my mind are:
/^\d+$/.match(value)
Number(value) == value
Forget regular expressions. JavaScript has a builtin function for this: isNaN()
:
isNaN(123) // false
isNaN(-1.23) // false
isNaN(5-2) // false
isNaN(0) // false
isNaN("100") // false
isNaN("Hello") // true
isNaN("2005/12/12") // true
Just call it like so:
if (isNaN( $("#whatever").val() )) {
// It isn't a number
} else {
// It is a number
}
With jQuery's validation plugin you could do something like this, assuming that the form is called form and the value to validate is called nrInput
$("form").validate({
errorElement: "div",
errorClass: "error-highlight",
onblur: true,
onsubmit: true,
focusInvalid: true,
rules:{
'nrInput': {
number: true,
required: true
}
});
This also handles decimal values.