简体   繁体   English

我的JavaScript正则表达式/正则表达式语法有什么问题?

[英]What's wrong with my JavaScript regex / regex syntax?

I need a regex to use with javascript/jquery that fits these rules... 我需要一个正则表达式来使用符合这些规则的javascript / jquery ...

  • it will include 10 digits 它将包括10位数字
  • if there is a leading 1 or +1 it should be ignored 如果有前导1+1则应忽略
  • valid characters allowed in the field are... 0-9 , () , and - 字段中允许的有效字符是... 0-9()-

I found a regex at Snipplr (the first one), but its not working. 我在Snipplr (第一个)找到了一个正则表达式,但它不起作用。 First of all, I'm not even sure if that regex fits my rules. 首先,我甚至不确定该正则表达式是否符合我的规则。 Secondly, its allowing inputs like &^%$$#%^adfafsd . 其次,它允许输入像&^%$$#%^adfafsd I believe the error is in my code not the regex. 我相信错误在我的代码而不是正则表达式。 For example, are there supposed to be quotes around the expression? 例如,表达式周围应该有引号吗?

Here is the code that is supposed to be validating the phone field... 这是应该验证电话字段的代码......

$('#phone').bind('blur', function() {
    var pattern = new RegExp("^(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})$");
    if(pattern.test($('#phone').val())){
        $("#phone").addClass("error");
        return false;
    }else{
        $("#phone").removeClass("error");
        return true;
    }
    return true;
})

When you're not using the literal form ( /[regex]/ ), you need to escape the regex string. 当您不使用文字形式(/ [regex] /)时,您需要转义正则表达式字符串。 Try this instead: 试试这个:

var regex = /^(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})$/;

if(regex.test($('#phone').val()){ ... }

if there is a leading 1 or +1 it should be ignored it will include 10 digits valid characters allowed in the field are... 0-9,(), and - 如果有一个前导1或+1,则应该忽略它将包括在该字段中允许的10位有效字符... 0-9,()和 -

That could be matched with an expression like: 这可以与表达式匹配:

/^(?:\+?1)?[()-]*(?:\d[()-]*){10}$/

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

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