69

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.

1
  • so you mean numbers and not digits ? Commented Sep 16, 2014 at 19:33

10 Answers 10

88

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');
   ...
}    
Sign up to request clarification or add additional context in comments.

2 Comments

the number can have decimals also. 5001.10 should be acceptable
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).
79

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
}

5 Comments

isNaN won't ensure your input doesn't contain whitespace. isNaN(" 42 ") === false
You can trim the whitespace with something like : YouValue.replace(/^\s\s*/, '').replace(/\s\s*$/, ''); More trim implementations : blog.stevenlevithan.com/archives/faster-trim-javascript
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().
@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 developer.mozilla.org/en/Core_JavaScript_1.5_Reference/… 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".
isNaN() is not reliable function to check valid numbers because it also returns false for boolean values for e.g. isNaN(true) -> return value = false
13

there is a simpler way of checking if a variable is an integer. you can use $.isNumeric() function. e.g.

$.isNumeric( 10 );     // true

this will return true but if you put a string in place of the 10, you will get false.

I hope this works for you.

1 Comment

The signature '(value: any): boolean' of '$.isNumeric' is deprecated.ts(6387)
2

Following script can be used to check whether value is valid integer or not.

  function myFunction() {
    var a = parseInt("10000000");
    if (!isNaN(a) && a <= 2147483647 && a >= -2147483647){
    alert("is integer"); 
    } else {
     alert("not integer"); 
    }
}

Comments

2
var yourfield = $('fieldname').val();

if($.isNumeric(yourfield)) { 
        console.log('IM A NUMBER');
} else { 
        console.log('not a number');
}

JQUERY DOCS:

https://api.jquery.com/jQuery.isNumeric/

Comments

1

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

3 Comments

Since your second example uses == and not ===, wouldn't type coercion on the right-hand-side cause the expression to be true always?
Don't know why no-one upvoated this answer. I used Number(value).... Its perfect.
@systemPAUSE The mention of user input and "digits" makes me think that the value is a string and the reason for the ==.
1

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.

Comments

1
String.prototype.isNumeric = function() {
    var s = this.replace(',', '.').replace(/\s+/g, '');
return s == 0 || (s/s);
}

usage

'9.1'.isNumeric() -> 1
'0xabc'.isNumeric() -> 1
'10,1'.isNumeric() -> 1
'str'.isNumeric() -> NaN

Comments

0

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

Comments

0
$(document).ready(function () {



    $("#cust_zip").keypress(function (e) {
        //var z = document.createUserForm.cust_mobile1.value;
        //alert(z);
        if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {

            $("#errmsgzip").html("Digits Only.").show().fadeOut(3000);
            return false;
        }
    });
});

1 Comment

Could you also add an explanation rather than just posting code?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.