admin管理员组

文章数量:1221922

I have a simple ajax form and I'm trying to validate that it

  1. has a value
  2. that value is a 10 digit number

I'm trying to use RegEx to do so. Here is what I have so far.

var reg = new RegExp("/[0-9]{10}/");
$("#call_form").bind("submit", function() {
       if ($("#call_number").val().length < 1 && reg.test($("#call_number").val())) {
               $("#call_error").show();
                return false;
        }
});

I know the problem has to do witht he RegExp as if I remove this portion of the code it validates that the box has a value.

EDIT: Here is the final regex I'm using

var regEx = new RegExp("/[0-9]/");

$("#call_form").bind("submit", function() {

    if ($("#call_number").val().length != 10 && !$("#call_number").val().match(regEx)) {
        $("#call_error").show();
        $.fancybox.resize();
        return false;
    }
});

EDIT 2 Using the suggestions here is what i'm usign which allows spaces and dashes that then get stripped on check

    $("#call_form").bind("submit", function() {
var Phone = $("#call_number").val().replace(/\D+/g,'');

if (Phone.length != 10) {
        $("#call_error").show();
        $.fancybox.resize();
        return false;

    }
});

I have a simple ajax form and I'm trying to validate that it

  1. has a value
  2. that value is a 10 digit number

I'm trying to use RegEx to do so. Here is what I have so far.

var reg = new RegExp("/[0-9]{10}/");
$("#call_form").bind("submit", function() {
       if ($("#call_number").val().length < 1 && reg.test($("#call_number").val())) {
               $("#call_error").show();
                return false;
        }
});

I know the problem has to do witht he RegExp as if I remove this portion of the code it validates that the box has a value.

EDIT: Here is the final regex I'm using

var regEx = new RegExp("/[0-9]/");

$("#call_form").bind("submit", function() {

    if ($("#call_number").val().length != 10 && !$("#call_number").val().match(regEx)) {
        $("#call_error").show();
        $.fancybox.resize();
        return false;
    }
});

EDIT 2 Using the suggestions here is what i'm usign which allows spaces and dashes that then get stripped on check

    $("#call_form").bind("submit", function() {
var Phone = $("#call_number").val().replace(/\D+/g,'');

if (Phone.length != 10) {
        $("#call_error").show();
        $.fancybox.resize();
        return false;

    }
});
Share Improve this question edited Apr 17, 2011 at 22:08 Brooke. asked Apr 17, 2011 at 7:33 Brooke.Brooke. 3,73113 gold badges52 silver badges82 bronze badges 7
  • That regex will only check to see if there's at least one number in the string. You should keep the {10} to ensure that it's all numbers. – beatgammit Commented Apr 17, 2011 at 7:59
  • @tjameson Ok, If I keep the {10} I should be able to ditch the length != 10 right? or is it better not to? – Brooke. Commented Apr 17, 2011 at 8:04
  • Yeah, but you should have both. reg.test will return true if the regexp matches any part of the string. – beatgammit Commented Apr 17, 2011 at 8:06
  • 1 Or you could anchor your RegExp using ^ and $: /^[0-9]{10}$/ I think is the syntax. – beatgammit Commented Apr 17, 2011 at 8:07
  • 3 I'd like to also point out that you seem to be ignoring the fact that people LOVE to put (555)555-5555 etc into phone number fields, I personally use 555.555.5555 all the time when typing my number into forms and hate it when some poorly written regexp denies me... I would suggest not validating the field at all, especially when you must consider +44 02 5555 5555 as well... You could also just .replace(/\D+/g,'') on the string to remove all non-numbers then check .length >= 10 to ensure at least 10 numbers... – gnarf Commented Apr 17, 2011 at 9:19
 |  Show 2 more comments

7 Answers 7

Reset to default 4

Here is what I use - its simple, just posting if someone is searching for the same.

var a = PHONE_FROM_FIELD;
var filter = /^[0-9-+]+$/;
if (filter.test(a)) {
     return true;
}
else {
     return false;
}

Cheers!

Your regex works fine for me... you could shorten it to just /[0-9]{10}/.

Your problem is here:

$("#call_number").val().length < 1. If the number is 10 characters long, it will never be less than 1, no?

You probably meant something like this:

$("#call_number").val().length === 10

No one has said what was wrong with your original effort - it's the slashes (/). When calling RegExp as a constructor, you don't need the slashes (which are a token to indicate a regular expression litteral), e.g.:

var re = /\w+/i;

is equivalent to:

var re = new RegExp('\\w+','i');

Note that you have to quote backslashes for special characters.

One last thing - allow spaces in the number. You might remove them before testing or storing though. Users find it much easier to read numbers in blocks of 3 or 4 digits, e.g.

  • 1234 871 098 is easier to read than 1234871098.

something like this:

var regEx = /^(\+\d)*\s*(\(\d{3}\)\s*)*\d{3}(-{0,1}|\s{0,1})\d{2}(-{0,1}|\s{0,1})\d{2}$/;
$("#call_form").bind("submit", function() {
       var val = $("#call_number").val();
       if (!val.match(regEx)) {
            $("#call_error").show();
            return false;
        }
});
function validate_Phone_Number() {
    var number = $('field_Id').val();
    var filter = /^((\+[1-9]{1,4}[ \-]*)|(\([0-9]{2,3}\)[ \-]*)|([0-9]{2,4})[ \-]*)*?[0-9]{3,4}?[ \-]*[0-9]{3,4}?$/;
    if (filter.test(number)) {
        return true;
    }
    else {
        return false;
    }
}

Here is a method that uses jQuery and the same validation for both keypress and keyup.

jQuery Code

    const goodColor = "#0C6";
    const badColor = "#FF0000";

    const $mobile_validation = $('#mobile_validation');
    
$('#mobile').on('keyup keypress', function(e) {
            if (e.which == 46 || e.which == 45 || e.which < 48 || e.which > 57) {
                    event.preventDefault();
                }
    
                if(this.value.length !=10 ){
                    $mobile_validation.text("Please enter 10 digit mobile number ");
                    $mobile_validation.css("color", badColor);
                }
    
                if(this.value.length ===10 ){
                    $mobile_validation.text("Good!");
                    $mobile_validation.css("color", goodColor);
                }
            });

HTML Code

<input type="text" id="mobile" class="form-control" name="telephone" maxlength="10">
<span id="mobile_validation"></span>
// check phone number validation
        function validatePhoneNumber(number)
        {
            count=number.length;
            if(number[0]!=" " && number[0]!="-" && number[count-1]!=" " && number[count-1]!="-")
            {
                temp=number.replace(" ", "");
                temp=temp.replace("-", "");
                if($.isNumeric(temp))
                {
                    if(temp.length>=7 && temp.length<=12)
                    {
                        flag=1;
                        for(i=1;i<count;i++)
                        {           
                            if(number[i]=="-" || number[i]==" ")
                            {
                                if(number[i-1]=="-" || number[i-1]==" " || number[i+1]=="-" || number[i+1]==" ")
                                {
                                    flag=0;
                                }
                            }               
                        }

                        if(flag==1)
                        {
                            valid=1;
                        }
                        else
                        {
                            valid=0;
                        }
                    }
                    else
                    {
                        valid=0;
                    }
                }
                else
                {

                    valid=0;
                }

            }
            else
            {
                valid=0;
            }
            return valid;
        }

本文标签: javascriptjQuery validate phone number with with RegExStack Overflow