Using the HTML5 Constraint API for Form Validation

Share this article

Key Takeaways

  • The HTML5 Constraint API simplifies form validation by allowing developers to avoid using JavaScript for basic validations, thereby making the process more user and developer-friendly.
  • Basic validation can be achieved by using appropriate values for the type attribute of input elements, such as “email” or “URL”. Additional validation attributes like pattern, required, maxlength, min, and max can be used to implement basic constraints.
  • For complex validation logic, the HTML5 Constraint API can be used to perform client-side validation and display error messages. The API includes a setCustomValidity() method that can be used to mark fields as valid or invalid and display custom error messages.
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.

Frequently Asked Questions on HTML5 Constraint API for Form Validation

What is the HTML5 Constraint API and why is it important for form validation?

The HTML5 Constraint API is a set of methods and properties available on form elements that allow you to create custom validation rules. It’s important for form validation because it provides a standardized way to ensure that user input meets certain criteria before it’s submitted. This can help prevent errors and improve the user experience by providing immediate feedback on the validity of their input.

How does the Constraint API differ from traditional JavaScript validation methods?

Traditional JavaScript validation methods often involve writing custom code for each form field. This can be time-consuming and error-prone. The Constraint API, on the other hand, provides a standardized set of methods and properties that can be used to validate form fields. This can make your code more efficient and easier to maintain.

Can I use the Constraint API with all types of form fields?

The Constraint API can be used with most types of form fields, including text fields, checkboxes, radio buttons, and select menus. However, it may not work with some types of custom form fields or fields created using third-party libraries.

How can I customize the error messages displayed by the Constraint API?

The Constraint API provides a setValidity method that allows you to set custom error messages. You can use this method in conjunction with the validationMessage property to display custom error messages when a form field fails validation.

Can I use the Constraint API to validate forms on the server-side?

The Constraint API is a client-side technology, meaning it runs in the user’s browser. However, you can use it in conjunction with server-side validation methods to provide a more robust validation solution. It’s important to always validate user input on the server-side, as client-side validation can be bypassed by malicious users.

How can I use the Constraint API to validate multiple form fields at once?

The Constraint API provides a checkValidity method that can be used to validate all the fields in a form at once. This method returns a boolean value indicating whether all the fields in the form are valid.

Can I use the Constraint API with forms created using HTML5 form elements?

Yes, the Constraint API is designed to work with HTML5 form elements. It provides a set of methods and properties that can be used to validate these elements and ensure that user input meets certain criteria.

How can I use the Constraint API to validate forms in real-time?

The Constraint API can be used in conjunction with JavaScript event listeners to validate form fields in real-time. For example, you could use the input event to validate a field each time the user types into it.

Can I use the Constraint API to validate forms in older browsers?

The Constraint API is a feature of HTML5, so it may not be supported in older browsers. However, you can use feature detection to check whether the Constraint API is available and provide a fallback validation method if it’s not.

How can I use the Constraint API to validate forms in a mobile context?

The Constraint API works in the same way on mobile devices as it does on desktop browsers. However, you may need to adjust your validation rules to account for the different input methods and screen sizes of mobile devices.

Sandeep PandaSandeep Panda
View Author

Sandeep is the Co-Founder of Hashnode. He loves startups and web technologies.

Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week