Kaigai Blog living abroad in my twenties

【My Study Note】Form Validation with Pattern Attribute

HTML Programming

Form Validation with Pattern Attribute

Telephone Numbers

<input type="tel" pattern="^\d{4}-\d{3}-\d{4}$" >

Alpha-Numeric Values

<input type="text" pattern="[a-zA-Z0-9]+" >

The following matches an alpha-numeric (combination of alphabets and numbers) character.

Twitter Username

<input type="text" pattern="^@[A-Za-z0-9_]{1,15}$" >

Hex Color Code

<input type="text" pattern="^#+([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$" >

This one matches a hexadecimal color. For example #3b5998 or #000.

URL input

<input type="url" pattern="https?://.+">

IPv4 Address input

<input type="text" pattern="\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}">

Date input pattern (dd/mm/yyyy or mm/dd/yyyy)

<input type="text" pattern="\d{1,2}/\d{1,2}/\d{4}">

Price input

<input type="text" pattern="\d+(\.\d{2})?">

Latitude/Longitude input

<input type="text" pattern="-?\d{1,3}\.\d+">

Giving Hints

<input type="text" name="ssn" pattern="^\d{3}-\d{2}-\d{4}$" title="The Social Security Number"/>

When you specify with “pattern”, it’s better to give the user the hint, which is the correct form.