jquery to validate phone number

后端 未结 9 1751
情话喂你
情话喂你 2020-12-01 06:34

I want to validate phone numbers like (123) 456-7890 or 1234567890 How should be the \'matches\' condition be written in the following code?

form.validate({         


        
相关标签:
9条回答
  • 2020-12-01 07:27

    If you normalize your data first, then you can avoid all the very complex regular expressions required to validate phone numbers. From my experience, complicated regex patterns can have two unwanted side effects: (1) they can have unexpected behavior that would be a pain to debug later, and (2) they can be slower than simpler regex patterns, which may become noticeable when you are executing regex in a loop.

    By keeping your regular expressions as simple as possible, you reduce these risks and your code will be easier for others to follow, partly because it will be more predictable. To use your phone number example, first we can normalize the value by stripping out all non-digits like this:

    value = $.trim(value).replace(/\D/g, '');

    Now your regex pattern for a US phone number (or any other locale) can be much simpler:

    /^1?\d{10}$/

    Not only is the regular expression much simpler, it is also easier to follow what's going on: a value optionally leading with number one (US country code) followed by ten digits. If you want to format the validated value to make it look pretty, then you can use this slightly longer regex pattern:

    /^1?(\d{3})(\d{3})(\d{4})$/

    This means an optional leading number one followed by three digits, another three digits, and ending with four digits. With each group of numbers memorized, you can output it any way you want. Here's a codepen using jQuery Validation to illustrate this for two locales (Singapore and US):

    http://codepen.io/thdoan/pen/MaMqvZ

    0 讨论(0)
  • 2020-12-01 07:28
    function validatePhone(txtPhone) {
        var a = document.getElementById(txtPhone).value;
        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(a)) {
            return true;
        }
        else {
            return false;
        }
    }
    

    Demo http://jsfiddle.net/dishantd/JLJMW/496/

    0 讨论(0)
  • 2020-12-01 07:30
    /\(?([0-9]{3})\)?([ .-]?)([0-9]{3})\2([0-9]{4})/
    

    Supports :

    • (123) 456 7899
    • (123).456.7899
    • (123)-456-7899
    • 123-456-7899
    • 123 456 7899
    • 1234567899
    0 讨论(0)
提交回复
热议问题