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
  2. can u please put up a demo for this, seems this code doesn't work...Indeed I copy the same the exact snippet into HTML5 page, it din't work

    ReplyDelete
  3. can u please put up a demo for this, seems this code doesn't work...Indeed I copied the same code snippet into HTML5 page, it din't work!!

    ReplyDelete
  4. In your markup specify the oninput handler for the input field:











    The check function is same as mentioned in the blog post. Let me know if this works for you.

    ReplyDelete
  5. Hi Sagar,
    Yes it works, Thank u very much for the wonderful code.

    Is there any way to change the look and feel of the error bubble?

    ReplyDelete
  6. I have not tried it, but looks like you can use pseudo classes to get the desired effect. Read this: http://adhockery.blogspot.in/2011/03/styling-with-html5-form-validation.html

    ReplyDelete
  7. Thanks, I tried few from the reference link, it works ;)

    ReplyDelete
  8. Thanks it saves my time.

    ReplyDelete
  9. This is an awesome post. Really very informative and creative contents. This concept is a good way to enhance knowledge. I like it and help me to development very well. Thank you for this brief explanation and very nice information. Well, got good knowledge.
    WordPress development company in Chennai

    ReplyDelete
  10. Nice post. Thanks for sharing! I want people to know just how good this information is in your article. It’s interesting content and Great work.
    Thanks & Regards,
    VRIT Professionals,
    No.1 Leading Web Designing Training Institute In Chennai.

    And also those who are looking for
    Web Designing Training Institute in Chennai
    Photoshop Training Institute in Chennai
    PHP & Mysql Training Institute in Chennai
    SEO Training Institute in Chennai
    Android Training Institute in Chennai


    ReplyDelete
  11. Hey, Your post is very informative and helpful for us.
    In fact i am looking this type of article from some days.
    Thanks a lot to share this informative article....best regards.
    websphere training in hyderabad

    ReplyDelete
  12. Check this website link https://college-homework-help.org/blog/bibliography and you will have a lot of writing solutions! Is this what are you looking for?

    ReplyDelete
  13. This is what I was looking for, thanks. Only professional writers can make such material. I really liked it. Finish university with a red diploma. This is possible thanks to pay for custom research paper. Take advantage of our services. Learning is easy.

    ReplyDelete
  14. Good job! Fruitful article. I like this very much. It is very useful for my research. It shows your interest in this topic very well. I hope you will post some more information about the software. Please keep sharing!!
    German Classes in Chennai
    German Language Classes in Chennai
    German Courses in Chennai
    German Language Course in Chennai
    CCNA Course in Chennai
    Cloud Computing Training in Chennai
    Data Science Course in Chennai
    German classes in Tambaram

    ReplyDelete
  15. I study HTML at university right now and, to be honest, it is pretty difficult for me. Besides I have to write an essay on this topic. But since I don't think I will make it good enough, I will go to https://www.essay-company.com/essay-writer. I heard they can do different academic writings of any difficulty in short terms, so this is the best choice for me.

    ReplyDelete
  16. Get many types of assignment help Dubai service from students assignment help and get the benefits of experts writing services that will boost your grades.

    ReplyDelete
  17. "Insightful" is the perfect word to describe this wonderful writing of yours. The artistic blend of this subject with your tone of writing made this a great read. Much love 😘.
    How to bottom

    ReplyDelete
  18. Welcome to the Customer Experience Survey. We value your candid feedback and appreciate you taking the time to complete our survey. Please enter the serial ...

    ReplyDelete
  19. Thanks for sharing great info … Hiring a limousine are excellent option to make your special occasion more delightful. Limo Hire MelbourneHummer Hire Melbourne.

    ReplyDelete
  20. Being fat is the biggest challenge, right? There are many reasons for being fat, and this makes us feel awkward at times.

    ReplyDelete
  21. Clearly explained about custom validation messages for html. Thanks for the clear blog. car hire melbourne airport | car rentals melbourne 

    ReplyDelete

Post a Comment

Popular posts from this blog

De-obfuscating javascript code in Chrome Developer Tools

I had blogged about JavaScript debugging with Chrome Developer Tools some time back, wherein I have explained how these developer tools can help in debugging javascript code. Today Google Chrome 12 was released and my Chrome browser was updated to this version. As with every release, there have been some improvements made on performance, usability etc,. One feature that stood out for me is the ability to De-obfuscate the javascript code.

What is Minification?

Minification is the process of removing unnecessary characters such as white spaces, comments, new lines from the source code. These otherwise would be added to make the code more readable. Minifying the source code helps in reducing the file size and thereby reducing the time taken to download the file. This is the reason why most of the popular javascript libraries such as jQuery are minified. A minified jQuery file is of 31 KB in size where as an uncompressed one is about 229 KB. Unfortunately, debugging minified javascript file…

Adding beforeRender and afterRender functions to a Backbone View

I was working on a Backbone application that updated the DOM when a response was received from the server. In a Backbone View, the initialize method would perform some operations and then call the render method to update the view. This worked fine, however there was scenario where in I wanted to perform some tasks before and after rendering the view. This can be considered as firing an event before and after the function had completed its execution. I found a very simple way to do this with Underscore's wrap method.