Validate phone number with JavaScript

前端 未结 26 1618

I found this code in some website, and it works perfectly. It validates that the phone number is in one of these formats:
(123) 456-7890 or 123-

相关标签:
26条回答
  • 2020-11-22 05:16

    What I would do is ignore the format and validate the numeric content:

    var originalPhoneNumber = "415-555-1212";
    
    function isValid(p) {
      var phoneRe = /^[2-9]\d{2}[2-9]\d{2}\d{4}$/;
      var digits = p.replace(/\D/g, "");
      return phoneRe.test(digits);
    }
    
    0 讨论(0)
  • 2020-11-22 05:16

    I have to agree that validating phone numbers is a difficult task. As for this specific problem i would change the regex from

    /^(()?\d{3}())?(-|\s)?\d{3}(-|\s)\d{4}$/
    

    to

    /^(()?\d{3}())?(-|\s)?\d{3}(-|\s)?\d{4}$/
    

    as the only one more element that becomes unnecessary is the last dash/space.

    0 讨论(0)
  • 2020-11-22 05:16
    \\(?\d{3}\\)?([\-\s\.])?\d{3}\1?\d{4}
    

    This will validate any phone number of variable format:

    \\(?\d{3}\\)? finds 3 digits enclosed by parenthesis or not.

    ([\-\s\.])? finds any of these separator characters or not

    \d{3} finds 3 digits

    \1 uses the first matched separator - this ensures that the separators are the same. So (000) 999-5555 will not validate here because there is a space and dash separator, so just remove the "\1" and replace with the separator sub-pattern (doing so will also validate non standard formats). You should however be format hinting for user input anyway.

    \d{4} finds 4 digits

    Validates:

    • (000) 999 5555
    • (000)-999-5555
    • (000).999.5555
    • (000) 999-5555
    • (000)9995555
    • 000 999 5555
    • 000-999-5555
    • 000.999.5555
    • 0009995555

    BTW this is for JavaScript hence to double escapes.

    0 讨论(0)
  • 2020-11-22 05:17

    realy simple

    "9001234567".match(/^\d{10}$/g)
    
    0 讨论(0)
  • 2020-11-22 05:19

    Try this one - it includes validation for international formats too.

    /^[+]?(1\-|1\s|1|\d{3}\-|\d{3}\s|)?((\(\d{3}\))|\d{3})(\-|\s)?(\d{3})(\-|\s)?(\d{4})$/g

    This regex validates the following format:

    • (541) 754-3010 Domestic
    • +1-541-754-3010 International
    • 1-541-754-3010 Dialed in the US
    • 001-541-754-3010 Dialed from Germany
    • 191 541 754 3010 Dialed from France
    0 讨论(0)
  • 2020-11-22 05:20

    Simple Regular expression: /\b\d{3}[-.]?\d{3}[-.]?\d{4}\b/g

    Check out the format, hope it works :
    444-555-1234
    f:246.555.8888
    m:1235554567

    0 讨论(0)
提交回复
热议问题