Wednesday, April 29, 2020

input type="tel" regex pattern for US 10-digit phone numbers

HTML5 has a <input type="tel"> but it's not very restrictive, in particular if you have an international audience, you need to think carefully.

For Porchfests, I think it's ok to assume "US", and my partners wanted some additional data validation. Building off the example on the MDN <input type="tel"> page:

<form>
      <input type="tel" id="phone" name="phone"
       pattern="\(?[0-9]{3}\)?[-\.\s]?[0-9]{3}[-\.\s]?[0-9]{4}"
       required>
      <small>Format: 123-456-7890</small>
      <button>go</button>
</form>

Optional parens around area code, and then space, dash, dot, or nothing between the 3/3/4 digit sections. That will allow variants like "(555)123-1234", "555-123-1234", "555.123.1234" or straight up "5551231234".

No comments:

Post a Comment