Validate phone number with JavaScript

前端 未结 26 1692

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

    If you are looking for 10 and only 10 digits, ignore everything but the digits-

       return value.match(/\d/g).length===10;
    
    0 讨论(0)
  • 2020-11-22 05:23

    Try this js function. Returns true if it matches and false if it fails Ref

    function ValidatePhoneNumber(phone) {
            return /^\+?([0-9]{2})\)?[-. ]?([0-9]{4})[-. ]?([0-9]{4})$/.test(phone);
    }

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

    Just ignore everything but digits.

    Here is what I use:

    // USA phones should contain at least 10 digits. For Ukrainian phones it's OK to have only 9 digits, without leading 0 and country code prefix: [+380] 88 888-88-88.
    String.prototype.isValidPhone = function(digitsCount) {
      var str = this.trim().match(/\d/g);
      return str && str.length >= (digitsCount || 10); // default is at least 10 digits
    }
    
    0 讨论(0)
  • 2020-11-22 05:25

    The following REGEX will validate any of these formats:

    (123) 456-7890
    123-456-7890
    123.456.7890
    1234567890

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

    Where str could be any of these formarts: 555-555-5555 (555)555-5555 (555) 555-5555 555 555 5555 5555555555 1 555 555 5555

    function telephoneCheck(str) {
      var isphone = /^(1\s|1|)?((\(\d{3}\))|\d{3})(\-|\s)?(\d{3})(\-|\s)?(\d{4})$/.test(str);
      alert(isphone);
    }
    telephoneCheck("1 555 555 5555");

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

    Just wanted to add a solution specifically for selecting non-local phone numbers(800 and 900 types).

    (\+?1[-.(\s]?|\()?(900|8(0|4|5|6|7|8)\3+)[)\s]?[-.\s]?\d{3}[-.\s]?\d{4}
    
    0 讨论(0)
提交回复
热议问题