Validate phone number with JavaScript

前端 未结 26 1615

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:11

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

    The ? character signifies that the preceding group should be matched zero or one times. The group (-|\s) will match either a - or a | character.

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

    I would suggest using something clearer (especially thinking to who will have to maintain the code)... what about:

    var formats = "(999)999-9999|999-999-9999|9999999999";
    var r = RegExp("^(" +
                   formats
                     .replace(/([\(\)])/g, "\\$1")
                     .replace(/9/g,"\\d") +
                   ")$");
    

    where the regexp is built from a clear template ? Adding a new one would then be a no-brainer and may be even the customer itself could be able to do that in a "options" page.

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

    This function worked for us well:

    let isPhoneNumber = input => {
    
      try {
        let ISD_CODES = [93, 355, 213, 1684, 376, 244, 1264, 672, 1268, 54, 374, 297, 61, 43, 994, 1242, 973, 880, 1246, 375, 32, 501, 229, 1441, 975, 591, 387, 267, 55, 246, 1284, 673, 359, 226, 257, 855, 237, 1, 238, 1345, 236, 235, 56, 86, 61, 61, 57, 269, 682, 506, 385, 53, 599, 357, 420, 243, 45, 253, 1767, 1809, 1829, 1849, 670, 593, 20, 503, 240, 291, 372, 251, 500, 298, 679, 358, 33, 689, 241, 220, 995, 49, 233, 350, 30, 299, 1473, 1671, 502, 441481, 224, 245, 592, 509, 504, 852, 36, 354, 91, 62, 98, 964, 353, 441624, 972, 39, 225, 1876, 81, 441534, 962, 7, 254, 686, 383, 965, 996, 856, 371, 961, 266, 231, 218, 423, 370, 352, 853, 389, 261, 265, 60, 960, 223, 356, 692, 222, 230, 262, 52, 691, 373, 377, 976, 382, 1664, 212, 258, 95, 264, 674, 977, 31, 599, 687, 64, 505, 227, 234, 683, 850, 1670, 47, 968, 92, 680, 970, 507, 675, 595, 51, 63, 64, 48, 351, 1787, 1939, 974, 242, 262, 40, 7, 250, 590, 290, 1869, 1758, 590, 508, 1784, 685, 378, 239, 966, 221, 381, 248, 232, 65, 1721, 421, 386, 677, 252, 27, 82, 211, 34, 94, 249, 597, 47, 268, 46, 41, 963, 886, 992, 255, 66, 228, 690, 676, 1868, 216, 90, 993, 1649, 688, 1340, 256, 380, 971, 44, 1, 598, 998, 678, 379, 58, 84, 681, 212, 967, 260, 263],
          //extract numbers from string
          thenum = input.match(/[0-9]+/g).join(""),
          totalnums = thenum.length,
          last10Digits = parseInt(thenum) % 10000000000,
          ISDcode = thenum.substring(0, totalnums - 10);
    
        //phone numbers are generally of 8 to 16 digits
        if (totalnums >= 8 && totalnums <= 16) {
          if (ISDcode) {
            if (ISD_CODES.includes(parseInt(ISDcode))) {
              return true;
            } else {
              return false;
            }
          } else {
            return true;
          }
        }
      } catch (e) {}
    
      return false;
    }
    
    console.log(isPhoneNumber('91-9883208806'));

    0 讨论(0)
  • 2020-11-22 05:14
    /^[+]*[(]{0,1}[0-9]{1,3}[)]{0,1}[-\s\./0-9]*$/g
    

    (123) 456-7890
    +(123) 456-7890
    +(123)-456-7890
    +(123) - 456-7890
    +(123) - 456-78-90
    123-456-7890
    123.456.7890
    1234567890
    +31636363634
    075-63546725

    This is a very loose option and I prefer to keep it this way, mostly I use it in registration forms where the users need to add their phone number. Usually users have trouble with forms that enforce strict formatting rules, I prefer user to fill in the number and the format it in the display or before saving it to the database. http://regexr.com/3c53v

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

    Everyone's answers are great, but here's one I think is a bit more comprehensive...

    This is written for javascript match use of a single number in a single line:

    ^(?!.*911.*\d{4})((\+?1[\/ ]?)?(?![\(\. -]?555.*)\( ?[2-9][0-9]{2} ?\) ?|(\+?1[\.\/ -])?[2-9][0-9]{2}[\.\/ -]?)(?!555.?01..)([2-9][0-9]{2})[\.\/ -]?([0-9]{4})$
    

    If you want to match at word boundaries, just change the ^ and $ to \b

    I welcome any suggestions, corrections, or criticisms of this solution. As far as I can tell, this matches the NANP format (for USA numbers - I didn't validate other North American countries when creating this), avoids any 911 errors (can't be in the area code or region code), eliminates only those 555 numbers which are actually invalid (region code of 555 followed by 01xx where x = any number).

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

    First off, your format validator is obviously only appropriate for NANP (country code +1) numbers. Will your application be used by someone with a phone number from outside North America? If so, you don't want to prevent those people from entering a perfectly valid [international] number.

    Secondly, your validation is incorrect. NANP numbers take the form NXX NXX XXXX where N is a digit 2-9 and X is a digit 0-9. Additionally, area codes and exchanges may not take the form N11 (end with two ones) to avoid confusion with special services except numbers in a non-geographic area code (800, 888, 877, 866, 855, 900) may have a N11 exchange.

    So, your regex will pass the number (123) 123 4566 even though that is not a valid phone number. You can fix that by replacing \d{3} with [2-9]{1}\d{2}.

    Finally, I get the feeling you're validating user input in a web browser. Remember that client-side validation is only a convenience you provide to the user; you still need to validate all input (again) on the server.

    TL;DR don't use a regular expression to validate complex real-world data like phone numbers or URLs. Use a specialized library.

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