如何从我的函数编写正则表达式模式以验证自定义 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
当最大长度== 13时:
- 仅包含:0-9+
- 第一个字符匹配:+
“+”后的 - 3 个字符必须是:161
当最大长度== 9时:
- 仅包含:0-9
有效数字示例:
- +161674773312
- 674773312
您可以使用的一个非常简单的方法是:
function isPhoneNumber(phone) {
if (phone.match(/^(?:\+161)?\d{9}$/) {
return true;
} else {
return false;
}
}
我有自己的函数来检查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
当最大长度== 13时:
- 仅包含:0-9+
- 第一个字符匹配:+ “+”后的
- 3 个字符必须是:161
当最大长度== 9时:
- 仅包含:0-9
有效数字示例:
- +161674773312
- 674773312
您可以使用的一个非常简单的方法是:
function isPhoneNumber(phone) {
if (phone.match(/^(?:\+161)?\d{9}$/) {
return true;
} else {
return false;
}
}