使用正则表达式验证 javascript 中的传真号码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15217333/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Validation for fax number in javascript using Regex
提问by milind
I have one requirement wherein I have to put a validation check on fax number using Regex.The accepted characters in fax number are + . and numbers from 0 to 9. For this I have written the following javascript function
我有一个要求,我必须使用正则表达式对传真号码进行验证检查。传真号码中接受的字符是 + 。和从 0 到 9 的数字。为此,我编写了以下 javascript 函数
function validateFax(checkField) {
if (checkField.value.length > 0) {
var faxRegEx = /[\+? *[1-9]+]?[0-9 ]+/;
if (!checkField.value.match(faxRegEx)) {
return false;
}
}
return true;
}
but it is not helping me to check all acceptable characters. Moreover it checks only 3 to 4 characters, but my fax number can consist of any number of characters. I am new to Regex. Can any one kindly tell me how can I modify this function to make it aligned to my requirement. Thanks in advance.
但这并不能帮助我检查所有可接受的字符。此外,它只检查 3 到 4 个字符,但我的传真号码可以包含任意数量的字符。我是正则表达式的新手。任何人都可以告诉我如何修改此功能以使其符合我的要求。提前致谢。
回答by Ali Shah Ahmed
/^\+?[0-9]+$/
The above regex would allow a +
sign at the beginning of the number. Then 0-9 can appear any number of times (more than equals to one). So this regex would allow: +123456789
123456789
etc.
If you want to limit the minimum number of digits, you can modify the regex in the following way:
上面的正则表达式允许+
在数字的开头有一个符号。那么 0-9 可以出现任意次数(大于等于 1)。所以这个正则表达式将允许:+123456789
123456789
等。
如果你想限制最小位数,你可以通过以下方式修改正则表达式:
/^\+?[0-9]{6,}$/
here {6,}
represents that [0-9] must appear at least6 times.
这里{6,}
表示 [0-9] 必须至少出现6 次。
回答by Michael W
This might do the trick:
这可能会奏效:
fax.match(/^\+?[0-9]{7,}$/);
I am assuming here that a fax number has at least 7 digits and the + in the beginning is optional.
我在这里假设传真号码至少有 7 位数字,并且开头的 + 是可选的。