Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
})
like image 259
Kirkland Avatar asked Mar 16 '26 00:03

Kirkland


1 Answers

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()){ ... }
like image 144
Jørgen Avatar answered Mar 17 '26 13:03

Jørgen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!