Thursday, May 23, 2024

Working with Regular Expressions in your HTML5 Forms

In an earlier article, we learned about HTML5 support for validation. One of the most powerful validations that HTML5 supports is the support for regular expressions and we will explore that in more detail in this article.



Regular expression is defined as text in a specific pattern. The short form of an American postal code (called zip code in US) is of numeric format of XXXXX, where each X is a number. An email has two alphanumeric text block joined by a ‘@’.

The postal code can be represented in regular expressions format as [0-9]{5}.

The above expression, [0-9]{5} can be interpreted as a number between 0 and 9 occurring 5 times.

Examples of valid postal code which match to the regular expression include 98052, 98109 and 10019.

Invalid values will be 2989, 8A362, etc.

Unlike the regular expression syntax used in programming languages, HTML5 does not require ‘^’ and ‘$’ to annotate the beginning and ending of values (it is assumed).


Regular expressions can be enforced on inputs by using the “pattern” attribute.


<input id=”phone” placeholder=”888-888-8888” title=”Text to convey pattern” required pattern=”[0-9]{3}-[0-9]{3}-[0-9]{4}”>

When the input does not adhere to the pattern, the browser can indicate to the user about the format using the contents of the “title” attribute.

Hands On

Here is a simple HTML5 listing showing how the “pattern” attribute works to enforce input in the desired format expressed as a regular expression.


<!DOCTYPE html>




        textarea:required:invalid, input:required:invalid {

            background-color: lightyellow;






        <h1>Regular Expressions demo</h1>

        <p>Demo showing HTML5 regular expression validation</p>




        <p>HTML Goodies</p>


    <form id=”myform action=”#”>

        <input id=”phone” placeholder=”888-888-8888″ title=”XXX-XXX-XXXX” required pattern=”[0-9]{3}-[0-9]{3}-[0-9]{4}”>

        <input id=”button1″ type=”submit”>





When this is rendered in a browser, and input in an incorrect format is entered, we can see the messaging which indicates bad input and suggested input format.




In this article, we learned about support for regular expressions in HTML5. I hope you have found this information useful.


About the author

Vipul Patel is a technology geek based in Seattle. He can be reached at . You can visit his LinkedIn profile at


Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Popular Articles