如何从我的函数编写正则表达式模式以验证自定义 phone 数字?

How to write regex pattern from my function for validation custom phone numbers?

我有自己的函数来检查phone个数:

function isPhoneNumber(phone) {
    var regexForPhoneWithCountryCode = /^[0-9+]*$/;
    var regexForPhoneWithOutCountryCode = /^[0-9]*$/;
    var tajikPhone = phone.substring(0,4);
    if(tajikPhone == "+161" && phone.length !== 13) {
        return false;
    } 
    if(phone.length == 9 && phone.match(regexForPhoneWithOutCountryCode)) {
        return true;
    } else if(phone.length > 12 && phone.length < 16 && phone.match(regexForPhoneWithCountryCode)) {
        return true;
    } else return false;
}

我的功能也可以,但不完全正确。

验证 phone 号码的规则:


当最大长度== 13时:


当最大长度== 9时:


有效数字示例:

您可以使用的一个非常简单的方法是:

function isPhoneNumber(phone) {
    if (phone.match(/^(?:\+161)?\d{9}$/) {
        return true;
    } else {
        return false;
    }
}