Validate phone number with JavaScript

前端 未结 26 2118

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

    This reg ex is suitable for international phone numbers and multiple formats of mobile cell numbers.

    Here is the regular expression: /^(+{1}\d{2,3}\s?[(]{1}\d{1,3}[)]{1}\s?\d+|+\d{2,3}\s{1}\d+|\d+){1}[\s|-]?\d+([\s|-]?\d+){1,2}$/

    Here is the JavaScript function

    function isValidPhone(phoneNumber) {
        var found = phoneNumber.search(/^(\+{1}\d{2,3}\s?[(]{1}\d{1,3}[)]{1}\s?\d+|\+\d{2,3}\s{1}\d+|\d+){1}[\s|-]?\d+([\s|-]?\d+){1,2}$/);
        if(found > -1) {
            return true;
        }
        else {
            return false;
        }
    }
    

    This validates the following formats:

    +44 07988-825 465 (with any combination of hyphens in place of space except that only a space must follow the +44)

    +44 (0) 7988-825 465 (with any combination of hyphens in place of spaces except that no hyphen can exist directly before or after the (0) and the space before or after the (0) need not exist)

    123 456-789 0123 (with any combination of hyphens in place of the spaces)

    123-123 123 (with any combination of hyphens in place of the spaces)

    123 123456 (Space can be replaced with a hyphen)

    1234567890

    No double spaces or double hyphens can exist for all formats.

提交回复
热议问题