Pinch
Pinch

Reputation: 4207

simple phone number regex not working

My Data: (222) 222-2222

Why is this not passing?

checkRegexp(TelephoneNumber, /^(d{3}) d{3}-d{4}$/, "Please enter your 10 digit phone number.");


function checkRegexp(o, regexp, n) {
              if (!(regexp.test(o.val()))) {
                  o.addClass("ui-state-error");
                  updateTips(n);
                  return false;
              } else {
                  return true;
              }
          }

Upvotes: 0

Views: 69

Answers (1)

dee-see
dee-see

Reputation: 24078

( and ) are special characters in regular expressions meant to capture groups, you need to escape them. You also want to have \d for the digit characters. Without the \ you are matching the letter d.

/^\(\d{3}\) \d{3}-\d{4}$/

When you have a problem with a regex, you can use a website like http://regex101.com/ that includes an explanation of your regular expression. You would have seen that the parentheses were not treated as literal characters.

For example, you original regex:

^ assert position at start of the string
1st Capturing group (d{3})
d{3} matches the character d literally (case sensitive)
Quantifier: Exactly 3 times
  matches the character   literally
d{3} matches the character d literally (case sensitive)
Quantifier: Exactly 3 times
- matches the character - literally
d{4} matches the character d literally (case sensitive)
Quantifier: Exactly 4 times
$ assert position at end of the string

You would have seen the problem easily.

Upvotes: 2

Related Questions