Client-Side Form Validation with HTML5

Tweet

When building web applications, it is important you take security seriously, especially when it has to do with collecting data from users.

It is a common maxim in security to trust nobody, hence never trust the user to enter correct or valid form values. For example, in an email form field, instead of entering a valid email address, the user might enter an invalid one or malicious data obviously ignoring the intent of the request.

When it comes to validating form values, it can be done on the client-side (web browser) and on the server-side (using your preferred server-side language).

In the past, client-side validation could only be achieved using JavaScript or using libraries from frameworks (think jQuery validation plugin). But that is changing or rather has changed because validation can now be done using HTML5 without having to write complex JavaScript validation code.

Form Validation with HTML5

HTML5 includes a fairly solid form validation mechanism powered by the following <input /> attributes: type, pattern, and require. Thanks to these new attributes in HTML5, you can delegate some data verification functions to the browser.

Let’s examine these new form attributes to see how they can aid form validation.

The type Attribute

This form attribute indicates what kind of input control to display such as the popular <input type="text" /> for handling simple text data.

Some form controls inherit validation systems without having to write any code. For example, <input type="email" /> validates the field to ensure the entered data is in fact a valid email address. If the field contains an invalid value, the form cannot be submitted for processing until it is corrected.

Invalid form value

Try the demo below by entering an invalid email:

See the Pen Email Validation Example by SitePoint (@SitePoint) on CodePen.

There is also <input type="number" />, <input type="url" /> and <input type="tel" /> for validating numbers, URLs, and telephone numbers respectively.

Note: The formatting of phone numbers varies from country to country due to the inconsistency in lengths and formats. As a result, the specification doesn’t define an algorithm for validating these, hence it isn’t supported web browsers at the time of writing.

Mind you, validation can be provided to tel using the pattern attribute which accepts a Regular Expression string, and which we’ll consider next.

The pattern Attribute

The pattern attribute will likely make a lot of developers, especially those working on the front-end, happy. This attribute specifies a format (in the form of a JavaScript Regular Expression) that the field value is checked against.

Regular expressions are a language used for parsing and manipulating text. They are often used to perform complex search-and-replace operations, and to ensure that text data is well-formed.

Today, regular expressions are included in most programming languages, as well as in many scripting languages, editors, applications, databases, and command-line tools.

Regular expressions (RegEX) provide a powerful, concise, and flexible means for matching strings of text such as particular characters, words, or patterns of characters.

By passing a RegEX string as the value for the pattern attribute, you can dictate what value is acceptable by the form field and also inform the user of errors.

Let’s see some examples of using regular expressions for validating form field data.

Telephone numbers:
As mentioned, the tel input type isn’t fully supported by web browsers due to the inconsistent format of telephone numbers across different countries.

For example, in my country, Nigeria, the telephone format is xxxx-xxx-xxxx which would be something like 0803-555-8205.

The RegEX ^\d{4}-\d{3}-\d{4}$ matches the format hence the input element would look like this:

<label for="phonenum">Phone Number:</label>
<input type="tel" pattern="^\d{4}-\d{3}-\d{4}$" > 

See the Pen Phone Number Validation Example by SitePoint (@SitePoint) on CodePen.

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

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

See the Pen Alpha-Numeric Character Validation Example by SitePoint (@SitePoint) on CodePen.

Twitter Username
This regular expression matches a Twitter username with the leading @ symbol. For example @tech4sky:

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

See the Pen Twitter Username Validation Example by SitePoint (@SitePoint) on CodePen.

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

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

See the Pen Hex-Color Code Validation Example by SitePoint (@SitePoint) on CodePen.

Giving Hints

To provide the user with a description of the pattern, or an error reporting on the field if an invalid value is entered, you can use the title attribute, like this:

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

Using the title attribute

Validating with the title attribute present

See the Pen hbuxg by SitePoint (@SitePoint) on CodePen.

If you’re new to Regular Expressions, you can check out this document on WebPlatform.org to give you a head start. In most cases, however, you should be able to use Google to search for the regular expression you want, or even use a tool to help you.

The required Attribute

This is a Boolean attribute used to indicate that a given input field’s value is required in order to submit the form. By adding this attribute to a form field, the browser requires the user to enter data into that field before submitting the form.

This replaces the basic form validation currently implemented with JavaScript, making things a little more usable and saving us some development time.

Example: <input type="text" name="my_name" required /> or <input type="text" name="my_name" required="required" /> for XHTML compatibility.

The required attribute

All the demos embedded above use the required attribute, so you can test those by trying to submit any of the forms without entering anything in the field.

Summary

Browser support for form validation features is pretty strong, and you can easily polyfill them where necessary.

It is worth noting that relying solely on the browser (client-side) for validation can be dangerous because it can be circumvented by a malicious user or by computer bots.

Not all browsers support HTML5, and not all input sent to your script will come from the form. This means that server-side side validation should also be in place before the form data is sent to the server for processing.

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • swsripon
  • Bruno Seixas

    We are getting to a point where everything is “from the box”, which is great =) Less third party js files.

  • Harry Oosterveen

    No need to cater for older browsers. You always have to validate on the server, and it makes it more user-friendly to validate on the client as well. On older browsers, the experience will be less nice, you get the feedback on faulty input after submitting, instead of before. One more reason to upgrade the browser, but not the problem of the developer :-)

  • http://alfy.me/ Ahmad Alfy

    For people ranting about older browsers … Use HTML5 form validation attributes and fall back to JS if it is not supported! Easy as this.

  • collizo4sky

    HTML5 is still evolving. Definitely in the future, this will change. You might want to fallback on using RegEX in the pattern attribute to ensure a proper email validation.

  • fdammassa

    Is it possible to style the validation messages?

  • Rakhi Dhavale

    Thanks Really Helped me!