简体   繁体   中英

What's wrong with my JavaScript regex / regex syntax?

I need a regex to use with javascript/jquery that fits these rules...

  • it will include 10 digits
  • if there is a leading 1 or +1 it should be ignored
  • valid characters allowed in the field are... 0-9 , () , and -

I found a regex at Snipplr (the first one), but its not working. First of all, I'm not even sure if that regex fits my rules. Secondly, its allowing inputs like &^%$$#%^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. 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 -

That could be matched with an expression like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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