Html5 Phone Number Validation with Parenthesis

Joseph Astrahan picture Joseph Astrahan · Jan 25, 2016 · Viewed 7.4k times · Source

Very simple question ... how do I validate in html5 for a pattern like this...

(562) 810-5566 or (714) 433-4434

Notice it will contain parenthesis and a space.

My current input control looks like this.

<input type="tel" data-tel-msg="Invalid Phone Number!" class="k-textbox" pattern="^\d{3}-\d{3}-\d{4}$" required />

I'm aware the current pattern matches 3334445555, but its not what I'm looking for, when I tried adding parenthesis the javascript console just gave an error incorrect regex syntax. Need help on the syntax here.

Also as a bonus, if you know how to get it to display a custom error message that would help also. Currently my data-tel-msg is not working.

Answer

Wiktor Stribiżew picture Wiktor Stribiżew · Jan 25, 2016

You can use the following code:

input:valid {
  color: green;
}
input:invalid {
  color: red;
}
<form name="form1">
 <input value="(555) 324-5643" type="tel" title="Invalid Phone Number!" class="k-textbox" pattern="[(][0-9]{3}[)] [0-9]{3}-[0-9]{4}" required />
 <input type="Submit"/> 
</form>

The regex \(\d{3}\)\s\d{3}-\d{4} matches strings in (###) ###-#### format since the HTML5 pattern is anchored (to the start and end of string) by default.

The title attribute allows showing error text.

If the backslashes are lost in your environment, just double them, or replace \d with [0-9]. To match a literal \( you can also use a character class: [(] (same for ): [)]). Inside a character class, these ( and ) lose their "special" grouping meaning.