Showing posts with label FORM Validation. Show all posts
Showing posts with label FORM Validation. Show all posts

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>
<html>
<head><meta charset="utf-8">
<title>HTML5 Sample Validation Page</title>
<style type="text/css">
body
{
    font-family:Arial;
    font-size:12px;
}
.valid
{
    color:#000000;
}
.invalid
{
    color:#FF0000;
}
</style>
</head>
<body>
<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>
<script>
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
        input.setCustomValidity('');
    }
    document.getElementById('validateMsg').innerHTML = 'Validation Message: "' + input.validationMessage + '"';
    document.getElementById('validity').innerHTML = 'checkValidity function output: "' + input.checkValidity() + '"';
}
</script>
</form>
</body>
</html>
Concept:
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.

Form Validation using checkValidity and Validity in HTML 5 using JavaScript- Sample Code

The next major version of the HTML standards (HTML 5) seem to have numerous improvements over the current standards. Most of the functionalities, for which the developers has to write extensive custom code, will get reduced to a certain extend by the launch of new standards.

The below sample shows how to perform a FORM validation for an HTML 5 input element using the newly introduced "Validity" property associated to an input element. This will also demonstrate the usage of checkValidity() function which can be used to identify whether the the form elements are all validated to proceed with the server communication.

Skill level: For Beginners

Sample Code:
<!DOCTYPE html>
<html>
<head><meta charset="utf-8">
<title>HTML5 Sample Validation Page</title>
<style type="text/css">
body
{
    font-family:Arial;
    font-size:12px;
}
.valid
{
    color:#000000;
}
.invalid
{
    color:#FF0000;
}
</style>
</head>
<body>
<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>
<script>
    function validate(input) {
        var out = document.getElementById('validateMsg');
        if (input.validity) {
            if (input.validity.valid === true) {
                out.innerHTML = "<span class='valid'>" + input.value +
                            " is a valid age.</span>";
            } else {
                out.innerHTML = "<span class='invalid'>" + input.value +
                            " is not valid age.</span>";
            }
        }
        document.getElementById('validity').innerHTML = "checkValidity() output: <span class='invalid'>" + input.checkValidity() + "</span>";
    }
</script> 
</form>
</body>
</html>

Concept:
The input element is a number element (that accepts "Age") in this example, with maximum and minimum values set in the design mode. [If more information is needed on the Input elements, refer here.] During the user input event, a JavaScript function validate() is called. This function validates the input value using the input.validity.valid property and provides appropriate message, after checking for the support of this functionality.

checkValidity() function is called to check and understand the value that it returns for the successful and unsuccessful validation scenarios.

Here are the output screens:

Valid Input:

Invalid Input:

As you can see, the checkValidity() always seems to return false. It returns true for values less than 10. It is being suspected that the inadequate browser support is one reason behind this weird behavior OR i'm missing something. However, as per the documentation here, this function will help us to check and trigger functions based on the invalid/valid state of one/multiple elements, thereby assisting us in form validations.

In the above code, the script tag is provided inside the body tag, for the sake of easy understanding. Keep it inside the HEAD tag, as it is usually done.