Home > OS >  The regular expression to validate a phone number doesn't work
The regular expression to validate a phone number doesn't work

Time:03-30

I create a regular expression to validate a phone number, but it doesn't work.


<form>
<label for="phone">Phone number:</label>
<input type="tel" name="phone" id="phone" required 
pattern="^\d{10}$|^\d{3}([\s-\.])\d{3}\1\d{4}$">
<button>Submit comment</button>
</form>

I use "an123456" to test, it's not a phone number, but it passed. I changed the "\s" in the pattern to " ", the regular expression worked correctly. So what's wrong with the "\s"?

CodePudding user response:

You need to fix your regex like this:

input:valid {
  color: navy
}
input:invalid {
  color: red;
}
<form>
  <label for="phone">Phone number:</label>
  <input type="tel" name="phone" id="phone" required pattern="\d{10}|\d{3}([\s.-])\d{3}\1\d{4}" />
  <button>Submit comment</button>
</form>

The final pattern will look like ^(?:\d{10}|\d{3}([\s.-])\d{3}\1\d{4})$ and it will match the full string due to automatically added anchors and the outer non-capturing group (no need adding them in the pattern).

Note that the pattern regex is compiled with u flag, and this means there are more escaping restrictions for the pattern. So, - must be at the end or start of the character class and you CAN'T escape the ., it MUST be unescaped since it is not any special regex metacharacter.

  • Related