Using the built-in pattern validation

In order to create more complex validation, we need to use JavaScript. To ease the development, the pattern attribute was introduced for the input fields. This enables us to use regex for making validation checks, and in this recipe we will take a look at some of the elements that can be used in it.

How to do it...

In this example, we will create a form using simple HTML as follows:

  1. First, we will add the form directly in the body section, starting with the Username field:
      <div>
        <label>
          Username: <input type="text" title="only letters allowed" name="username" pattern="^[a-zA-Z]+$" />
        </label>
      </div>
  2. Then, we will add Phone as follows:
     <div> <label> Phone <input type="tel" name="phone" pattern="[\+]?[1-9]+" /> ...

Get HTML5 Data and Services Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.