Skip to main content

Custom validation messages for HTML5 Input elements using the constraint validation API

HTML5 has introduced several input types such as EMAIL, URL, RANGE, SEARCH, DATE, TIME, etc,. Most of the modern browsers have implemented them and are ready to be used in a HTML document. Another exciting feature introduced in HTML5 is the form validation. Instead of writing JavaScript to validate users input, browsers can now validate it and show an appropriate message if the validation fails. The validation message is shown in line with the field for which the validation has failed. The default error message is shown when the validation fails. In this post I'll explain how these error messages can be changed.

Take an example of a form that has an input element with type="email" and a submit button:

<form id="myForm">
<input id="eid" name="email_field" type="email" />
<input type="submit" />
</form>



After entering some text in the input field and on clicking the submit button, the default validation message is shown:

The message style varies from browser to browser and the one shown in this picture is taken from Google's Chrome browser.

As you can see, message "Please enter an email address." is shown when the user enters an invalid email address and clicks the submit button. This message is shown inline with the input field.



To show a custom message, instead of default one the constraint validation API is used. Here the user can set the custom validation message using element.setCustomValidity(message):

function check(input) {  
    if(input.validity.typeMismatch){  
        input.setCustomValidity("Dude '" + input.value + "' is not a valid email. Enter something nice!!");  
    }  
    else {  
        input.setCustomValidity("");  
    }                 
}  
From the code, the function check accepts a HTMLInputElement (input) as a parameter and checks for the validity of the input text entered against its type using input.validity.typeMismatch. It is set to true if the entered text doesn't match the specified input type. The input.setCustomValidity(message) is then used to set the validation message. Now whenever the validation fails the custom message will be shown:

Similarly the custom validation message can be set in various conditions, such as required filed not entered - element.validity.valueMissing, element value doesn't match the pattern - element.validity.patternMismatch, value is lower than the provided minimum - element.validity.rangeUnderflow, value is higher than the maximum - element.validity.rangeOverflow.



One can set such validation messages in various use cases as well. Say, when the entered text is not one of the expected values or when the confirmation email address doesn't match with the original email address. In such cases showing a custom validation message comes very handy.

Comments

  1. Thanks for the useful guidelines, I am sure it will be helpful both to my brother and I - we are only beginners in API, but I hope with this tutorial we will figure everything out - as they say, two minds are better than one. Once again, thanks for posting!

    ReplyDelete

Post a Comment

Popular posts from this blog

File upload and Progress events with HTML5 XmlHttpRequest Level 2

The XmlHttpRequest Level 2 specification adds several enhancements to the XmlHttpRequest object. Last week I had blogged about cross-origin-requests and how it is different from Flash\Silverlight's approach .  With Level 2 specification one can upload the file to the server by passing the file object to the send method. In this post I'll try to explore uploading file using XmlHttpRequest 2 in conjunction with the progress events. I'll also provide a description on the new HTML5 tag -  progress which can be updated while the file is being uploaded to the server. And of course, some ColdFusion code that will show how the file is accepted and stored on the server directory.

How to use the APP_INITIALIZER token to hook into the Angular bootstrap process

I've been building applications using Angular as a framework of choice for more than a year and this post is not about another React vs Angular or the quirks of each framework. Honestly, I like Angular and every day I discover something new which makes development easier and makes me look like a guy who built something very complex in a matter of hours which would've taken a long time to put the correct architecture in place if I had chosen a different framework. The first thing that I learned in Angular is the use of the APP_INITIALIZER token.

On GraphQL and building an application using React Apollo

When I visualize building an application, I would think of using React and Redux on the front-end which talks to a set of RESTful services built with Node and Hapi (or Express). However, over a period of time, I've realized that this approach does not scale well when you add new features to the front-end. For example, consider a page that displays user information along with courses that a user has enrolled in. At a later point, you decide to add a section that displays popular book titles that one can view and purchase. If every entity is considered as a microservice then to get data from three different microservices would require three http  requests to be sent by the front-end app. The performance of the app would degrade with the increase in the number of http requests. I read about GraphQL and knew that it is an ideal way of building an app and I need not look forward to anything else. The GraphQL layer can be viewed as a facade which sits on top of your RESTful services o...