I am a complete newbie when it comes to regular expressions. Even after reading guides about them, I still have a hard time formulating my own. I am trying to get my form to validate the fax number in the +12345678910 format. I have some code, but it allows me to submit mixed numbers and letters, as well as submit data with blank spaces and without filling out the faxnum text box completely. I would strongly appreciate any help with the form and tips on how to become more proficient with regex.
在正则表达式方面,我是一个完整的新手。即使在阅读了关于他们的指南之后,我仍然很难制定自己的指南。我想让我的表单以+12345678910格式验证传真号码。我有一些代码,但它允许我提交混合数字和字母,以及提交带有空格的数据,而不是完全填写faxnum文本框。我非常感谢有关如何更加熟练使用正则表达式的表单和提示的任何帮助。
var fax = document.registration.faxnum;
faxval(fax);
function faxval(fax)
{
var numbers = /[\+? *[1-9]+]?[0-9 ]+/; //Bad regex
if (fax.value.match(numbers))
{
document.getElementById("faxmsg").innerHTML=("Everything is OK.");
faxmsg.style.color="green";
}
else
{
faxmsg.innerHTML=("Invalid fax number.");
faxmsg.style.color="red";
}
};
1 个解决方案
#1
1
To match a number like +12345678910, try: \+1[2-9][0-9]{9}
要匹配+12345678910之类的数字,请尝试:\ +1 [2-9] [0-9] {9}
I assume that the +1 portion is the international number code, 234 is the area code, 567 is the exchange and 8910 is the rest of the number. This pattern would also match a number such as +12125551212.
我假设+1部分是国际号码,234是区号,567是交换,8910是其余的号码。此模式也会匹配一个数字,如+12125551212。
The first digit of any U.S. or Canadian phone number must be 2 through 9. So we can allow that as the first character ([2-9]
). Then the rest of the number will be 9 digits long, 0 through 9 ([0-9]{9}
).
任何美国或加拿大电话号码的第一个数字必须是2到9.所以我们可以允许它作为第一个字符([2-9])。然后剩下的数字将是9位数字,0到9([0-9] {9})。
If you want to allow - or . too, you can use: \+1(|\.|\-)[2-9][0-9]{2}(|\.|\-)[0-9]{3}(|\.|\-)[0-9]{4}
. The (|\.|\-)
part means "allow no character OR a . character OR a - character."
如果你想允许 - 或者。你也可以使用:\ _1 +(| \。| \ - )[2-9] [0-9] {2}(| \。| \ - )[0-9] {3}(| \。 | \ - )[0-9] {4}。 (| \。| \ - )部分表示“不允许字符或字符或字符”。
#1
1
To match a number like +12345678910, try: \+1[2-9][0-9]{9}
要匹配+12345678910之类的数字,请尝试:\ +1 [2-9] [0-9] {9}
I assume that the +1 portion is the international number code, 234 is the area code, 567 is the exchange and 8910 is the rest of the number. This pattern would also match a number such as +12125551212.
我假设+1部分是国际号码,234是区号,567是交换,8910是其余的号码。此模式也会匹配一个数字,如+12125551212。
The first digit of any U.S. or Canadian phone number must be 2 through 9. So we can allow that as the first character ([2-9]
). Then the rest of the number will be 9 digits long, 0 through 9 ([0-9]{9}
).
任何美国或加拿大电话号码的第一个数字必须是2到9.所以我们可以允许它作为第一个字符([2-9])。然后剩下的数字将是9位数字,0到9([0-9] {9})。
If you want to allow - or . too, you can use: \+1(|\.|\-)[2-9][0-9]{2}(|\.|\-)[0-9]{3}(|\.|\-)[0-9]{4}
. The (|\.|\-)
part means "allow no character OR a . character OR a - character."
如果你想允许 - 或者。你也可以使用:\ _1 +(| \。| \ - )[2-9] [0-9] {2}(| \。| \ - )[0-9] {3}(| \。 | \ - )[0-9] {4}。 (| \。| \ - )部分表示“不允许字符或字符或字符”。