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
    Replies
    1. Great Article. Thank you for sharing! Really an awesome post for every one.

      IEEE Final Year projects Project Centers in Chennai are consistently sought after. Final Year Students Projects take a shot at them to improve their aptitudes, while specialists like the enjoyment in interfering with innovation. For experts, it's an alternate ball game through and through. Smaller than expected IEEE Final Year project centers ground for all fragments of CSE & IT engineers hoping to assemble. Final Year Project Domains for IT It gives you tips and rules that is progressively critical to consider while choosing any final year project point.

      JavaScript Training in Chennai

      JavaScript Training in Chennai

      Delete
  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. I like the helpful info you provide in your articles. I’ll bookmark your weblog and check again here regularly. I am quite sure I will learn much new stuff right here! Good luck for the next!
    Google ads services
    Google Ads Management Services
    Google Ads Management Company
    Google advertising agency
    Google Ads Management agency
    Google ad services on phone
    Google advertising company
    Google advertising agency

    ReplyDelete
  10. Awesome post. I am a normal visitor of your blog and appreciate you taking the time to maintain the excellent site. I’ll be a frequent visitor for a long time.

    ACP Sheet
    ACP Sheet Price
    Aluminium Composite Panel
    ACP Panel
    ACP Sheets

    ReplyDelete
  11. PaperNow is a writing service where you can find the best writers, and you can buy essay for your college assignments.
    Don;t lose your chance to get the highest score at class and impress all of your peers.

    ReplyDelete
  12. Hello, I have browsed most of your posts. This post is probably where I got the most useful information for my research. Thanks for posting, maybe we can see more on this. Are you aware of any other websites on this subject.
    tree trimmers greenacres

    ReplyDelete
  13. Superbly written article, if only all bloggers offered the same content as you, the internet would be a far better place.
    bathroom remodel fresno ca

    ReplyDelete
  14. I think this is one of the most significant information for me. And i’m glad reading your article. But should remark on some general things, The web site style is perfect, the articles is really great : D. Good job, cheers.
    air conditioning repair west palm beach

    ReplyDelete
  15. Thanks for a wonderful share. Your article has proved your hard work and experience you have got in this field. Brilliant .i love it reading.
    painting companies in west palm beach

    ReplyDelete
  16. You have a good point here!I totally agree with what you have said!!Thanks for sharing your views...hope more people will read this article!!! patio screen repair west palm beach

    ReplyDelete
  17. You have a good point here!I totally agree with what you have said!!Thanks for sharing your views...hope more people will read this article!!!
    bathroom remodelers south florida

    ReplyDelete
  18. I have read your article, it is very informative and helpful for me.I admire the valuable information you offer in your articles. Thanks for posting it..
    bathroom remodeling miami beach fl

    ReplyDelete
  19. Hello, I have browsed most of your posts. This post is probably where I got the most useful information for my research. Thanks for posting, maybe we can see more on this. Are you aware of any other websites on this subject. hvac repair palm beach gardens

    ReplyDelete
  20. Prices at everyone's fingertips

    The company offers competitive prices unparalleled for its presence inside any other place suitable for all strata and classes of society.
    شركة مكافحة النمل الابيض بالقطيف
    شركة مكافحة حشرات بالقطيف
    شركة رش مبيدات بالقطيف
    ارخص شركة مكافحة حشرات

    ReplyDelete
  21. This post is probably where I got the most useful information for my research.
    residential contractor south florida

    ReplyDelete
  22. I like your post ! thanks for sharing.
    best airdrops

    ReplyDelete
  23. it is informative post for me ! keep it up
    bitquence

    ReplyDelete
  24. it is very informative and helpful for me.
    kandol lake

    ReplyDelete
  25. You started looking for a real college literature lesson homework help online because of some extraordinary sophisticated assignment that is due soon and you have no clue about a way to approach to its completion.
    Let’s first be clear on one thing: you buy at http://homeworkanswer.org and we give great homework help. College demands it. And you don’t have to be involved if you are uninclined to do so. You can give us the assignment, explain what you will, and leave us to complete the work. However, our methodology is set up so that you can reap enormous benefits from the process itself. From the day you complete the buying process, you will get to choose your professional writer, and e-mail communication begins immediately.

    ReplyDelete
  26. This is the first & best article to make me satisfied by presenting good content. I feel so happy and delighted.By Learn Digital Marketing Course Training in Chennai it will help to get Digital Marketing Course Training in Chennai.Learn Best Digital Marketing Course Training in Chennai's professional institute to get reputed job.

    ReplyDelete
  27. Hello Admin!

    Thanks for the post. It was very interesting and meaningful. I really appreciate it! Keep updating stuffs like this. If you are looking for the Advertising Agency in Chennai / Printing in Chennai , Visit us now..

    ReplyDelete
  28. Thanks for sharing this great information .
    latest airdrop

    ReplyDelete
  29. We agree that you always need something new or trending news that's why here are the technology news for you.

    ReplyDelete
  30. When I originally left a comment I seem to have clicked the -Notify me when new comments are added- checkbox and now every time a comment is added I get four emails with the exact same comment. Is there a way you are able to remove me from that service? Thank you!
    kbc number

    ReplyDelete
  31. מזל שנתקלתי בכתבה הזאת. בדיוק בזמן
    קבוצת גבאי

    ReplyDelete
  32. This comment has been removed by the author.

    ReplyDelete
  33. This is the last touching common mistake. Many people either do not pack properly, or they leave it to the last minute. Start preparing when you decide to move one and start scanning items that you no longer use; sell a yard to collect some extra cash. Later, as soon as you confirm the sale, you can start increasing your packaging and organizing.
    شركة نقل اثاث
    شركة نقل عفش بالخرج

    ReplyDelete
  34. keep up the good work. this is an Assam post. this to helpful, i have reading here all post. i am impressed. thank you. this is our digital marketing training center. This is an online certificate course
    digital marketing training in bangalore | https://www.excelr.com/digital-marketing-training-in-bangalore

    ReplyDelete
  35. 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!!
    SEO Training in Bangalore
    SEO Course in Bangalore
    SEO Training Institute in Bangalore
    Best SEO Training Institute in Bangalore
    SEO Training Bangalore

    ReplyDelete
  36. אהבתי מאוד את סגנון הכתיבה.
    טבעות אירוסין

    ReplyDelete
  37. תמשיכו בפרסום פוסטים מעניינים כמו זה. תודה.

    קייטרינג לאירוע

    ReplyDelete
  38. אין ספק שזה אחד הנושאים המעניינים. תודה על השיתוף
    שולחנות אוכל

    ReplyDelete
  39. הדעות שלי קצת חלוקות בעניין הזה אבל ללא ספק כתבת מעניין מאוד.
    מזותרפיה לשיער

    ReplyDelete
  40. אין ספק שזה אחד הנושאים המעניינים. תודה על השיתוף.
    שולחן אוכל

    ReplyDelete
  41. תודה על השיתוף. מחכה לכתבות חדשות.
    משטח פעילות לתינוק

    ReplyDelete
  42. בדיוק מה שחיפשתי. תודה רבה.
    נכס מניב

    ReplyDelete
  43. The best way to spend your night in 31 Dec with Hong Kong Escorts Girls, call us for bookings

    ReplyDelete
  44. It's enlightening and you're clearly inconceivably fit round there. You have opened my eyes to changing viewpoints on this factor with an amazing and strong substancehttps dissertation helps

    ReplyDelete
  45. This comment has been removed by the author.

    ReplyDelete
  46. Cane Corso - Information, Characteristics, Facts, Names
    https://www.dogbreedslist.info/all-dog-breeds/Cane-Corso-Italiano.html

    ReplyDelete
  47. American Wirehair - Information, Characteristics, Facts, Names
    https://www.catbreedslist.com/all-cat-breeds/American-Wirehair.html

    ReplyDelete
  48. Top 10 Fastest Motorcycles In The World
    https://www.carlogos.org/reviews/10-fastest-motorcycles-in-the-world.html

    ReplyDelete
  49. רציתי רק לשאול, אפשר לשתף את הפוסט בבלוג שלי?
    התקנת אינטרקום

    ReplyDelete
  50. רציתי רק לשאול, אפשר לשתף את הפוסט בבלוג שלי?
    אינטרקום לבית פרטי

    ReplyDelete
  51. כל מילה. תודה על השיתוף, מחכה לעוד פוסטים בנושא.
    חברת ניהול מוניטין

    ReplyDelete
  52. סגנון כתיבה מרענן, תודה על השיתוף.
    תמונה על עץ

    ReplyDelete
  53. Shweta gaur is one of the famous makeup artist in all over India. We are providing the best makeup artist courses and more other courses in over branches in Delhi.
    Bridal Makeup
    Makeup Artist in Delhi
    Makeup Artist
    Best Makeup Artist in Delhi
    Best Makeup Artist in East Delhi
    Top Makeup Artist in Delhi

    ReplyDelete
  54. Thanks for sharing informative article with us...
    PHP Training in Bangalore - BTM | PHP Training Institutes | PHP Course Syllabus | PHP Course Fee - My Training Bangalore
    - PHP Training in Bangalore, BTM - My Training Bangalore offers Best PHP Training with Expert Real-time PHP Trainers who have 8+ Years of Expertise,
    Know more about PHP Details, Syllabus, Duration and Fees, we also provide placement assistance on successful completion of the Course.

    ReplyDelete
  55. The ats resume checker is the ebst way to review your papers with the high attention and exclude all mistakes. The professional writing services can provide you with such a tool.

    ReplyDelete
  56. I really appreciate this wonderful post that you have provided for us. I assure this would be beneficial for most of the people. Thanks for sharing the information keep updating, looking forward to more posts. High Quality Product Images

    ReplyDelete
  57. May I simply say what a relief to find someone who genuinely knows what they're discussing on the net. You definitely realize how to bring a problem to light and make it important. More people should read this and understand this side of the story. I was surprised you are not more popular since you surely have the gift.
    Tech news

    ReplyDelete
  58. Thanks for the interesting blog that you have implemented here. Very helpful and innovative. Waiting for your next upcoming article.
    Digital Marketing Course In Kolkata

    ReplyDelete


  59. This post is very good thanks for sharing its very amazing post...Here, Sarkari result adda website, you can find information about the latest RRB Recruitment 2020

    ReplyDelete
  60. This blog gives the good knowledge to us. know more about Bathroom remodeling chandler

    ReplyDelete
  61. Such a very useful article. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article. data analytics courses

    ReplyDelete
  62. Nice post. Thanks for sharing! I want people to know just how good this information is in your blog. It’s interesting content and Great work
    data analytics course
    Business Analytics Certification Course Training in Hyderabad
    <a href="https://360digitmg.com/india/python-r-programming/''>Python and R Programming Course Training for Beginners</a>

    ReplyDelete
  63. Thanks for the interesting blog that you have implemented here. Very helpful and innovative. Waiting for your next upcoming article.
    Java training in chennai
    Java training institute in chennai
    Java course in chennai
    Java training classes
    Java training
    Java programming classes
    core java coure
    <a

    ReplyDelete
  64. Hello Admin!

    Thanks for the post. It was very interesting and meaningful. I really appreciate it! Keep updating stuffs like this. If you are looking for the Advertising Agency in Chennai | Printing in Chennai , Visit Inoventic Creative Agency Today..

    ReplyDelete
  65. I really happy found this website eventually. Really informative and inoperative, Thanks for the post and effort! Please keep sharing more such blog.

    norton.com/setup

    www.spectrum.net/login

    kaspersky activation

    aolmail.com

    aolmail.com

    mcafee.com/activate

    ReplyDelete
  66. Awesome blog. I enjoyed reading your articles. This is truly a great read for me. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work!
    Data Science Certification in Bangalore

    ReplyDelete
  67. Two full thumbs up for this magneficent article of yours. I've really enjoyed reading this article today and I think this might be one of the best article that I've read yet. Please, keep this work going on in the same quality.
    Data Science Course in Bangalore

    ReplyDelete
  68. You re in point of fact a just right webmaster. The website loading speed is amazing. It kind of feels that you're doing any distinctive trick. Moreover, The contents are masterpiece. you have done a fantastic activity on this subject!
    Data Science Training in Bangalore

    ReplyDelete
  69. Nice blog. I finally found great post here Very interesting to read this article and very pleased to find this site. Great work!
    Data Science Training in Pune
    Data Science Course in Pune

    ReplyDelete
  70. I would like to thank you for the efforts you have made in writing this article. I am hoping the same best work from you in the future as well. In fact your creative writing abilities has inspired me to start my own Blog Engine blog now. Really the blogging is spreading its wings rapidly. Your write up is a fine example of it.

    Data Science Course

    ReplyDelete
  71. Took me time to read all the comments, but I really enjoyed the article. It proved to be Very helpful to me and I am sure to all the commenters here! It’s always nice when you can not only be informed, but also entertained!

    Data Science Training

    ReplyDelete
  72. Wow! Such an amazing and helpful post this is. I really really love it. It's so good and so awesome. I am just amazed. I hope that you continue to do your work like this in the future also.
    Data Science Course in Bangalore

    ReplyDelete
  73. It is perfect time to make some plans for the future and it is time to be happy. I’ve read this post and if I could I desire to suggest you few interesting things or tips. Perhaps you could write next articles referring to this article. I want to read more things about it!
    Data Science Training in Bangalore

    ReplyDelete

Post a Comment

Popular posts from this blog

A cheat sheet of keyboard shortcuts in ColdFusion Builder

In my last post I have explained about keyboard shortcuts in ColdFusion Builder 2.0. This blog post contains a list of all shortcut keys and I have listed these keyboard shortcuts based on the categories that it falls into. Well, this post was not planned since users can easily get to know the keyboard shortcuts by navigating to the preferences (ColdFusion -> Profiles -> Keys). However, I met Joshua at Scotch on the rocks in Edinburgh and he suggested that it would be nice to have the list of keyboard shortcuts handy. So this post is for those who would like to have the list with them and refer it whenever required.


Keyboard shortcuts for inserting text:

These are the keyboard shortcuts which are used to insert some text into the editor:

CommandKeyboard shortcuts on WindowsKeyboard shortcuts on MacInsert anchor tagCTRL + T, LCMD + T, LInsert bold tagCTRL + T, BCMD + T, BInsert br tagCTRL + T, RCMD + T, RInsert cfabortCTRL + T, ACMD + T, AInsert cfdumpCTRL + T, DCMD + T, DInsert cfs…

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…