checking if number entered is a digit in jquery

JavascriptJqueryValidation

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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');
   ...
}    

Solution 2 - Javascript

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
}

Solution 3 - Javascript

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.

Solution 4 - Javascript

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"); 
    }
}

Solution 5 - 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

Solution 6 - Javascript

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.

Solution 7 - Javascript

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

Solution 8 - Javascript

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/

Solution 9 - Javascript

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

Solution 10 - Javascript

$(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;
        }
    });
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionOmnipresentView Question on Stackoverflow
Solution 1 - Javascriptkarim79View Answer on Stackoverflow
Solution 2 - JavascriptPlutorView Answer on Stackoverflow
Solution 3 - JavascriptYoweli KachalaView Answer on Stackoverflow
Solution 4 - JavascriptM ArifView Answer on Stackoverflow
Solution 5 - JavascriptAtes GoralView Answer on Stackoverflow
Solution 6 - JavascriptLars AndrenView Answer on Stackoverflow
Solution 7 - Javascriptk2flView Answer on Stackoverflow
Solution 8 - JavascriptPodTech.ioView Answer on Stackoverflow
Solution 9 - JavascriptPlatinum AzureView Answer on Stackoverflow
Solution 10 - JavascriptSandip SinghView Answer on Stackoverflow