Reputation: 9072
How do I validate for a pattern like this...
(562) 810-5566 or (714) 433-4434
Note that 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 it's not what I'm looking for, when I tried adding parenthesis the JavaScript console just gave an error incorrect regex syntax.
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.
Upvotes: 2
Views: 9553
Reputation: 626794
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.
Upvotes: 5