Tuesday, March 19, 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.

 

Basics

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.

e.g.

<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>

<html>

<head>

    <style>

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

            background-color: lightyellow;

        }

    </style>

</head>

<body>

    <header>

        <h1>Regular Expressions demo</h1>

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

    </header>

    <footer>

        <h1></h1>

        <p>HTML Goodies</p>

    </footer>

    <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”>

    </form>

</body>

</html>

 

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.

 

 

Summary

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 vipul.patel@hotmail.com . You can visit his LinkedIn profile at https://www.linkedin.com/pub/vipul-patel/6/675/508

 

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Popular Articles

Featured