Ilja
Ilja

Reputation: 46479

Check If only numeric values were entered in input. (jQuery)

I would like to check if users enter correct phone number in, with help of jQuery, so far I got to this stage:

var phone = $("input#phone").val();
if (phone !== "") {
    //Check if phone is numeric
    $("label#phone_error").show(); //Show error
    $("input#phone").focus(); //Focus on field
    return false;
}

Basically it checks if phone number was entered and if it was, I would like to check if it is a numeric value and if it is not display the error messages. Could anyone help with checking if it is numeric?

Upvotes: 31

Views: 166821

Answers (10)

Abdul Hameed
Abdul Hameed

Reputation: 1043

You can use jQuery method to check whether a value is numeric or other type.

$.isNumeric()

Example

$.isNumeric("46")

true

$.isNumeric(46)

true

$.isNumeric("dfd")

false

Upvotes: 10

Prateju Patil
Prateju Patil

Reputation: 90

I used this kind of validation .... checks the pasted text and if it contains alphabets, shows an error for user and then clear out the box after delay for the user to check the text and make appropriate changes.

$('#txtbox').on('paste', function (e) {
            var $this = $(this);
            setTimeout(function (e) {
                if (($this.val()).match(/[^0-9]/g))
                {
                    $("#errormsg").html("Only Numerical Characters allowed").show().delay(2500).fadeOut("slow");                       
                    setTimeout(function (e) {
                        $this.val(null);
                    },2500);
                }                   
            }, 5);
        });

Upvotes: 1

mix3d
mix3d

Reputation: 4333

This isn't an exact answer to the question, but one other option for phone validation, is to ensure the number gets entered in the format you are expecting.

Here is a function I have worked on that when set to the onInput event, will strip any non-numerical inputs, and auto-insert dashes at the "right" spot, assuming xxx-xxx-xxxx is the desired output.

<input oninput="formatPhone()">

function formatPhone(e) {
    var x = e.target.value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
    e.target.value = !x[2] ? x[1] : x[1] + '-' + x[2] + (x[3] ? '-' + x[3] : '');
}

Upvotes: 0

Bhanu Pratap
Bhanu Pratap

Reputation: 1761

 if (!(/^[-+]?\d*\.?\d*$/.test(document.getElementById('txtRemittanceNumber').value))){
            alert('Please enter only numbers into amount textbox.')
            }
            else
            {
            alert('Right Number');
            }

I hope this code may help you.

in this code if condition will return true if there is any legal decimal number of any number of decimal places. and alert will come up with the message "Right Number" other wise it will show a alert popup with message "Please enter only numbers into amount textbox.".

Thanks... :)

Upvotes: 2

James-Jesse Drinkard
James-Jesse Drinkard

Reputation: 15703

I used this to check if all the text boxes had numeric values:

if(!$.isNumeric($('input:text').val())) {
        alert("All the text boxes must have numeric values!");
        return false;
    }

or for one:

$.isNumeric($("txtBox").val());

Available with jQuery 1.7.

Upvotes: 4

Ze Zinatiitude
Ze Zinatiitude

Reputation: 11

for future visitors, you can add this functon that allow user to enter only numbers: you will only have to add jquery and the class name to the input check that into http://jsfiddle.net/celia/dvnL9has/2/

$('.phone_number').keypress(function(event){
var numero= String.fromCharCode(event.keyCode);
 var myArray = ['0','1','2','3','4','5','6','7','8','9',0,1,2,3,4,5,6,7,8,9];
index = myArray.indexOf(numero);// 1
var longeur= $('.phone_number').val().length;
if(window.getSelection){
 text = window.getSelection().toString();
 } if(index>=0&text.length>0){
  }else if(index>=0&longeur<10){
    }else {return false;} });

Upvotes: 1

Yoosaf Abdulla
Yoosaf Abdulla

Reputation: 3978

I used this:

jQuery.validator.addMethod("phoneUS", function(phone_number, element) {
phone_number = phone_number.replace(/\s+/g, ""); 
return this.optional(element) || phone_number.length > 9 &&
    phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
}, "Please specify a valid phone number");

Upvotes: 3

Jorge Zapata
Jorge Zapata

Reputation: 2336

There is a built-in function in jQuery to check this (isNumeric), so try the following:

var phone = $("input#phone").val();
    if (phone !== "" && !$.isNumeric(phone)) {
  //Check if phone is numeric
  $("label#phone_error").show(); //Show error
  $("input#phone").focus(); //Focus on field
  return false;
}

Upvotes: 29

devnull69
devnull69

Reputation: 16544

Try this ... it will make sure that the string "phone" only contains digits and will at least contain one digit

if(phone.match(/^\d+$/)) {
    // your code here
}

Upvotes: 65

Tango Bravo
Tango Bravo

Reputation: 3309

http://docs.jquery.com/Plugins/Validation/CustomMethods/phoneUS

Check that out. It should be just what you're looking for. A US phone validation plugin for jQuery.

If you want to do it on your own, you're going to be in for a good amount of work. Check out the isNaN() function. It tells you if it is not a number. You're also going to want to brush up on your regular expressions for validation. If you're using RegEx, you can go without isNaN(), as you'll be testing for that anyway.

Upvotes: 3

Related Questions