简体   繁体   English

JavaScript注册表格中用于传真号码验证的正则表达式

[英]Regular expression for fax number validation in a JavaScript registration form

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. 我正在尝试获取表格以验证+12345678910格式的传真号码。 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. 我有一些代码,但是它允许我提交混合数字和字母,以及提交带有空格的数据,而无需完全填写Faxnum文本框。 I would strongly appreciate any help with the form and tips on how to become more proficient with regex. 我非常感谢您提供有关如何更熟练使用正则表达式的表格和提示的帮助。

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";
    }
};

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. 我假设+1部分是国际号码代码,234是区号,567是交换局,8910是号码的其余部分。 This pattern would also match a number such as +12125551212. 此模式还将匹配一个数字,例如+12125551212。

The first digit of any US or Canadian phone number must be 2 through 9. So we can allow that as the first character ( [2-9] ). 美国或加拿大电话号码的首位数字必须为2到9。因此,我们可以将其作为首字符( [2-9] )。 Then the rest of the number will be 9 digits long, 0 through 9 ( [0-9]{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} . 您也可以使用: \\+1(|\\.|\\-)[2-9][0-9]{2}(|\\.|\\-)[0-9]{3}(|\\.|\\-)[0-9]{4} The (|\\.|\\-) part means "allow no character OR a . character OR a - character." (|\\.|\\-)部分的意思是“不允许字符或。字符或-字符”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM