views:

2036

answers:

5

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.

+4  A: 

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');
   ...
}
karim79
deleted mine :) this way is much more elegant
Michael
the number can have decimals also. 5001.10 should be acceptable
Omnipresent
@Omnipresent - sorry, but you did say isDigit, I'll edit.
karim79
Should have specified that. :-) You can use a regex like this for ALL (well, many) possible numbers: `/^[+-]?\d+(\.\d+)?([eE][+-]?\d+)?$/` This will allow for decimals, signs, and even scientific notation on the end if you want. You can remove various parts as you need to (Google Perl-style regular expressions if you need help figuring out which part is what, but it should be fairly intuitive).
Platinum Azure
A: 

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.

Link: http://www.regular-expressions.info/javascript.html

Platinum Azure
A: 

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
Ates Goral
Since your second example uses == and not ===, wouldn't type coercion on the right-hand-side cause the expression to be true always?
system PAUSE
+2  A: 

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
}
Plutor
isNaN won't ensure your input doesn't contain whitespace. isNaN(" 42 ") === false
Ates Goral
You can trim the whitespace with something like : YouValue.replace(/^\s\s*/, '').replace(/\s\s*$/, '');More trim implementations : http://blog.stevenlevithan.com/archives/faster-trim-javascript
Doomspork
Interesting approach, but personally I think the regex is clearer than the double negative (not a Not-a-Number is a number). Although I'd be inclined to put the regex into a nice utility function isDigit().
system PAUSE
@karim79: it's not the case that isNaN won't accept a string argument. isNaN("42") returns false, isNaN("42.2") returns false, isNaN("42.2.3") returns true. The documentation at https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Functions/isNaN states that "isNaN attempts to convert the passed parameter to a number. If the parameter can't be converted, it returns true; otherwise, it returns false".
NickFitz
@NickFitz - I stand corrected.
karim79
A: 

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.

Lars Andren