Quick Tip: Easy form validation with HTML5

By Danny Markov

easy-form-validation-html5

When you collect information from people through a form, applying some kind of validation is a must. Failing to do so could lead to lost customers, junk data in your database or even security exploits of your website. Historically, building form validation has been a pain. On the server side, this is made easier by full stack frameworks which handle it for you, but on the client you often end up with JavaScript libraries that take a lot of effort to integrate.

Thankfully, HTML5 gives us a number of features that can handle most of your validation needs. Forms in HTML5 now have built-in support for validation through the use of special attributes and new input types, and give you a lot of control over styling with CSS.

Form Validation with HTML5

See an online demo here and read a quick overview of the basics behind HTML5 form validation below.

1. Specialized Input Types

HTML5 introduced several new input types. They can be used to create input boxes, which will accept only a specified kind of data.

The new input types are as follows:

  • color
  • date
  • datetime
  • datetime-local
  • email
  • month
  • number
  • range
  • search
  • tel
  • time
  • url
  • week

To use one of the new types, include them as the value of the type attribute:

<input type="email"/>

If the browser does not support the given input type, the field will behave as a regular text input. Also, it’s helpful to know that some of the input fields (such as “email” and “tel”) will cause a mobile devices to open specialized keyboards with a limited set of keys, and not the full QUERTY layout.

For more details on all the input types, head out to this MDN wiki – here.

2. Required Fields

By simply adding the “required” attribute to a , or