Using the HTML5 Constraint API for Form Validation

Sandeep Panda
Share

Validating web forms has always been a painful task for many developers. Performing client side validation in a user- as well as developer-friendly way is really hard. Furthermore informing users about the validation error in a pleasant way is a tedious task. HTML5 constraint validation API helps developers avoid use of JavaScript for simple validations.

For complex validation logic, the API can be used for performing client side validation and displaying error messages very easily. In this tutorial I will give you an overview of the HTML5 constraint validation API and discuss how to use it in your projects for creating better web forms.

Before going any further, check out this compatibility chart to be sure which features supported by your browser. Just note that, though the HTML5 constraint validation API offers an excellent way to validate form fields, a server side validation must always be done.

Basic Constraint Validation

Basic validation can be performed by choosing the most appropriate values for the type attribute of input elements. For example, you can validate an email by writing the following HTML:

<input type=”email” />		//The field value must be an email

You can validate a URL by writing the following markup:

<input type=”URL” />			// The field value must be a URL

By using email or url as a value for the type attribute, a constraint is automatically added and the fields are validated automatically when the form is submitted. The browser also displays an error message in a very user friendly way if any validation errors occur.

There are also several validation based attributes you can use within your form. The following are some of the attributes that can be used to implement basic constraints:

  1. pattern: The pattern attribute is used to specify a regular expression and the field value must match this pattern. This attribute can be used with input types like text, password, email, url, tel and search.
    For example, The following HTML snippet uses a pattern attribute for an input field.
    <input type=”text” pattern=”[1-4]{5}” />

    When the form is submitted, validation is performed on the input field. As a result, a value like ABCD won’t pass the validation, in this case.

  2. required: A required attribute indicates that a value must be specified for the input element.
    <input type=”text” required />

    The above snippet makes use of the required attribute. If you leave the field empty and try to submit the form, a validation error will occur.

  3. maxlength: This is an integer value that specifies the maximum number of characters allowed for a particular input field.
    <input type=”text” maxlength=”20” />

    The above snippet adds an upper limit to the input field. The value entered in this input element must be less than 20 characters long.

  4. min & max: As the names suggest, the min and max attributes specify the lower and upper limit respectively for an input element.

Handling Complex Constraints

Complex validation logics can be easily handled using the HTML5 constraint API. For example, you can have a password field and a confirm password field. You need to ensure that the values in both the fields are the same at the time of submission. If not, an error message should be displayed to the user. This can actually be done very easily with the HTML5 constraint API.

First, we need to attach an onchange listener to password fields. The following snippet shows the HTML form.

<form name="ValidationForm">
	Password: <input type="password" id="password1"/>
	Confirm Password:<input type="password" id="password2"/>
	<input type="submit" value="submit"/>
</form>

As there will be no submit event until all the fields are completely validated, there is really no way to know when the form is submitted. That’s why we are interested in the change event. Whenever a change event is fired, we need to check if both of the passwords match. If yes, we call setCustomValidity() on the input element (password field in this case) with an empty string as the argument.

This means that the password field is marked as valid and therefore when the form is submitted there will be no validation error. On the other hand, if we detect that the passwords don’t match in a change event we call setCustomValidity() with an error message as argument. It means the password field will be marked as invalid and the error message will be shown when the user submits the form.

The following JavaScript implements this logic:

<script type="text/javascript">
window.onload = function () {
	document.getElementById("password1").onchange = validatePassword;
	document.getElementById("password2").onchange = validatePassword;
}
function validatePassword(){
var pass2=document.getElementById("password2").value;
var pass1=document.getElementById("password1").value;
if(pass1!=pass2)
	document.getElementById("password2").setCustomValidity("Passwords Don't Match");
else
	document.getElementById("password2").setCustomValidity('');	 
//empty string means no validation error
}
</script>

The best part about using the above approach is that you need not worry about how to present the error message to the user. You just need to call a simple method — setCustomValidity() — with appropriate arguments and the error message will be displayed accordingly.

Conclusion

You can implement many simple to advanced constraints using the HTML5 constraint validation API.

The API offers a huge set of tools for customizing the validation process. We have just discussed a part of the API.

To know about more advanced concepts like CSS hooks, validity states check out this tutorial at Mozilla.