Friday, December 17, 2010

Provide custom validation messages using setCustomValidity in HTML 5 pages

If you have come through my other note on "Form validations on HTML 5", you already know that HTML 5 is promising enough to make validations better and native. Just set the right properties for the INPUT elements and HTML 5 gives you on-the-fly validations with less code. But, in some scenarios, we might have to include additional logical validations, in which case, setCustomValidity() function can be used to logically decide and set your own validation messages.

Below is a simple sample code that will demonstrate the usage of setCustomValidity() functionality.
<!DOCTYPE html>
<head><meta charset="utf-8">
<title>HTML5 Sample Validation Page</title>
<style type="text/css">
<form id="form1" method="post">
<label>Age: <input type="number" required="true" value="50" min="18" max="60" step="1" oninput="validate(this)"> (between 18 and 60)</label><br /><br />
<div id="validateMsg"></div><br />
<div id="validity"></div>
function validate(input) {
    //logically decide and set custom validation message
    if (input.value == "20" || input.value == "30") {
        // set custom validation message
        input.setCustomValidity('Your Age (' + input.value + ') is in a transition phase.');
    } else {
        // reset the validation message - makes it valid for checkValidity function
    document.getElementById('validateMsg').innerHTML = 'Validation Message: "' + input.validationMessage + '"';
    document.getElementById('validity').innerHTML = 'checkValidity function output: "' + input.checkValidity() + '"';
In this example, Age input is expected to accept only values between 18 and 60. Additionally, 20 and 30 ages are also treated as Invalid (of course, unusual scenario). This is done by using setCustomValidity() function which will internally set the validationMessage property of the input control. The HTML 5 form validation function checkValidity() takes the validationMessage in to account and provides output as shown below, in Google Chrome.

Valid Input:

Invalid Input:

Custom In-valid Input: (20 and 30 are not accepted):

In valid scenarios, validationMessage is an empty string and checkValidity function returns true. In In-valid scenarios, including our custom invalid scenarios, checkValidity function returns false and validationMessage is returned based on the custom message set.


  1. Thank you, So Useful

  2. thanks! very useful to me! I've been searching on how to handle validation in html5

  3. here's a working sample: