<div class="formRow">
<label for="phone">Phone number</label>
<input name="custPhone" id="phone" type="tel" placeholder="(nnn) nnn-nnnn"
pattern="^d{10}$|^((d{3})s*)?d{3}[s-]?d{4}$" >
</div>
This comes from a textbook (albeit a few years old) and I don’t know why the browser just accepts anything.
Can anyone see what might be preventing the regex from doing its job to get 7 or 10 digit phone numbers to be validated and other patterns to be rejected?
When I take just the expression and test at regex101.com, the expression seems to do its job there.
^d{10}$|^((d{3})s*)?d{3}[s-]?d{4}$
On regex101.com 1234567 will match and 1234567890 will match and other patterns with fewer than 7, more than 10 and patterns with 8, and 9 digits will be rejected.
The textbook’s other regex validation is fine.
It doesn’t seem to be related to the browser as it fails with two different browsers.
I’m stumped.
2
Answers
From documentation:
This means your actual pattern is
^(?:^d{10}$|^((d{3})s*)?d{3}[s-]?d{4}$)$
– browser explicitly adds start and end symbols, so your RegEx becomes invalid.What you can do here is to validate form via JS:
The value provided to a
pattern
attribute is converted into a regular expression with thev
flag for unicode sets.The HTML standard defines that:
In
v
/ unicode sets mode, it is mandatory to escape a single dash inside a character class even if it is next to a bracket. Demo:Therefore, the
-
in[s-]
needs to be escaped in HTML: