Reputation: 6110
I have three different input fields for the phone numbers. Each field should only allow US phone number format. Here is example:
(564) 332-9088 //allowed format.
User should be able to enter phone number only in the format I have above in example. So first three digits should be in the braces ()
then space (can be ignored) followed with 3 digits and then -
dash and last four digits. I have created pattern regex but that won't require ()
. User can enter phone number in this format as well 336-678-8999
that should not be allowed.
<form name="testFrm" id="testFrm" method="POST" action="#">
<label for="wphone">Work Phone:</label>
<input type="tel" name="phoneW" id="phoneW" pattern="(?:\(\d{3}\)|\d{3})[- ]?\d{3}[- ]?\d{4}" maxlength="14" title="US based Phone Number in the format of: (123) 456-7890" placeholder="(xxx) xxx-xxxx" required />
<span><input type="submit" name="frmSubmit" id="frmSubmit" value="Submit" /></span>
</form>
If anyone knows how I can adjust my code to accept only (xxx) xxx-xxxx
please let me know or if you have better way to approach this problem.
Upvotes: 1
Views: 4783
Reputation: 38552
I think this will work for you to allow only (xxx) xxx-xxxx
format. Here space is optional after the (xxx)
\(\d{3}\)[ ]?\d{3}[-]?\d{4}
Explanation
\(
-> matches the character ( literally (case sensitive)
\d
-> matches a digit (equal to [0-9])
{3}
-> Quantifier — Matches exactly 3 times
\)
-> matches the character ) literally (case sensitive)
[ ]?
-> Matches space between zero and one times, as many times as possible, giving back as needed (greedy)
\d
-> matches a digit (equal to [0-9])
{3}
-> Quantifier — Matches exactly 3 times
[-]?
-> Matches dash between zero and one times, as many times as possible, giving back as needed (greedy)
\d
-> matches a digit (equal to [0-9])
{4}
-> Quantifier — Matches exactly 4 times
See demo : https://regex101.com/r/Ws3c1t/1
Upvotes: 4