Faizan Qadri
Faizan Qadri

Reputation: 248

Check validation for numbers only

following is my piece of code which checks if the input format is EMAIL which comes from the form input or not and validates accordingly i want to know how can i modify the following code that validates if the input was only number

  if(email.length == 0 || email.indexOf('@') == '-1'){
                var error = true;
                $('#email_error').fadeIn(500);
            }else{
                $('#email_error').fadeOut(500);
            }

Upvotes: 1

Views: 1661

Answers (4)

Marc
Marc

Reputation: 11613

if (email.match(/[0-9]+/)) {
   //it's all numbers
}

EDIT As mentioned in the comments, to ensure that the entry is ALL numbers, the regex would have to include the begin and end characters, ^ and $:

if (email.match(/^[0-9]+$/)) {
   //it's all numbers
}

Or even more succinctly:

if (email.match(/^\d+$/)) {
   //it's all numbers
}

I don't deserve the credit for that fix, but I did want to correct it for anyone who may come find this later.

Upvotes: 2

ajax333221
ajax333221

Reputation: 11754

I would use:

if(isNaN(email*1)){
    //evaluated to NaN
}else{
    //evaluated to number
}

In this case the (email*1) have the possibility to evaluate to NaN, and thus will fail the check because the list of falsish values are 0,"",false,null,undefined,NaN

Upvotes: 1

Elliot Bonneville
Elliot Bonneville

Reputation: 53291

Check if converting the email address to a Number object returns a 'Not a Number' value; if not, the input was a number. The code would look like this:

if(!isNaN(Number(email)) {

Upvotes: 1

Chris Gessler
Chris Gessler

Reputation: 23113

Use jQuery's IsNumeric method.

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

$.isNumeric("-10");  // true

Upvotes: 2

Related Questions