HTML5 input validation with pattern regexes

Working on a homework assignment that requires validation of user input into HTML forms. HTML5 is great because it can do validation for you. Here are some examples:

For a last name accept any alpha characters, space, apostrophe, or dash. Some names do have apostrophes such as O’Malley. Some names might have dashes for example if someone marries and keeps their original last name along with the new last name. And spaces can exist for names like Van Allen. I set this to require two or more characters. I guess someone could have a last name like Ai but I think only one character would probably never occur.


[code language=”html”]<input maxlength="50" name="lname" pattern="[A-Za-z ‘-]{2,}" required="" type="text" placeholder="Last" />[/code]

First name is a little more simple since I don’t think apostrophes will occur but spaces or dashes might:


[code language=”html”]<input maxlength="50" name="fname" pattern="[A-Za-z -]{2,}" required="" type="text" placeholder="First" />[/code]

For street address I accept alpha and numeric characters, spaces, dashes, periods, and hash signs. I set the minimum to 5 which is kind of arbitrary but its hard to imagine an address being shorter than 5 characters:


[code language=”html”]<input maxlength="50" name="saddress" pattern="[0-9A-Za-z ‘#\.-]{5,}" required="" size="50" type="text" placeholder="Street address" />[/code]

For state I set a dropdown select which reads from an array of state names, so no validation to worry about.

For ZIP code I allow a 5 digit or optional 9 digit ZIP. Note the use of the () to group the optional ZIP +4 characters:


[code language=”html”]<input maxlength="10" name="zip" pattern="\d{5}([\-]\d{4})?" required="" size="10" type="text" placeholder="ZIP" />[/code]

For telephone I set the input type to “tel” and still use a pattern:


[code language=”html”]<input maxlength="12" name="tel" pattern="\d{3}-\d{3}-\d{4}" size="12" type="tel" placeholder="555-555-1234" />[/code]

Finally, here is a cool site which has even more HTML5 input pattern regexes.

HTML5 is cool!