Open In App

Form required attribute with a custom validation message in HTML5

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

The creation of web forms has perpetually been a fancy task. whereas marking up the shape itself is simple, checking whether or not every field features a valid and coherent price is tougher, and informing the user concerning the matter might become a headache. HTML5 introduced new mechanisms for forms. There 2 kinds of Constraint Validation DOM Methods which are checkValidity() & setCustomValidity(). Let’s know more about them.

checkValidity() method

We first use the checkValidity() method to check if the input fields contain valid data and run checkValidity() on form submit in order to validate all form fields. If a minimum of one is invalid, the validation fails. By using the checkValidity() method, we validate each of the input element on blur event or each of the select element on change event. This allows the user to know if a selected field is valid or invalid at a given time, and makes it attainable to convey the user feedback promptly.

Syntax:

input="this.checkValidity()"

This is going to return true if an input element contains valid data.

Example: This example shows how to do HTML form required attribute along with setting custom validation message.




<!DOCTYPE html>
  
<html>
  
<head>
    <title>Form required Attribute | With message validation</title>
</head>
  
<body>
  
    <body style="text-align:center;">
  
        <h1 style="color:green">GeeksforGeeks</h1>
  
        <p>Enter a number and click the button:</p>
  
        <input id="gfg" type="number" min="101" max="999" required>
  
        <button onclick="myFunction()">Try it</button>
  
        <p>An message will display of ERROR, if the number
           is lesser than 101 or greater than 999</p>
        <p id="geeks"></p>
  
        <script>
            function myFunction() {
                var inpObj = document.getElementById("gfg");
                if (!inpObj.checkValidity()) {
                    document.getElementById("geeks")
                              .innerHTML = inpObj.validationMessage;
                } else {
                    document.getElementById("geeks")
                              .innerHTML = "Input is ALL RIGHT";
                }
            }
        </script>
  
    </body>
  
</html>


    Output:

  • When we load the code:
    ngcut
  • When we leave the field blank and click the button:
    ngcut
  • When you enter an invalid value:
    ngcut
  • When you enter a valid value:
    ngcut

setCustomValidity()

In an input element, it is used to set the validationMessage property. It is really very easy to control a custom validation message in an HTML5 form. Let us find out how.

Syntax:

input="this.setCustomValidity()"

This part is of utmost importance, as it will hide the error message when the user will enter the new data.

Example: This example shows how to do HTML form required attribute along with setting custom validation message.




<!DOCTYPE html>
  
<html>
  
<head>
    <title>Form required Attribute | With custom message validation
    </title>
</head>
  
<body>
    <center>
  
        <h1 style="color:green">GeeksforGeeks</h1>
  
        <form id="myform">
            <p>Enter an Email Id:</p>
            <input id="email" oninvalid="InvalidMsg(this);" 
                   oninput="InvalidMsg(this);" name="email" 
                   type="email" required="required" />
            <input type="submit" />
        </form>
    </center>
  
    <script>
        function InvalidMsg(textbox) {
  
            if (textbox.value === '') {
                textbox.setCustomValidity
                      ('Entering an email-id is necessary!');
            } else if (textbox.validity.typeMismatch) {
                textbox.setCustomValidity
                      ('Please enter an email address which is valid!');
            } else {
                textbox.setCustomValidity('');
            }
  
            return true;
        }
    </script>
  
</body>
  
</html>


    Output:

  • When we load the code:
    ngcut
  • When we leave the field blank and click the button:
    ngcut
  • When you enter an invalid Email Id:
    ngcut
    Three types of Constraint Validation DOM Properties:

  • validationMessage : When the validity is false, it contains the message a browser will display.
  • willValidate: It will indicate when the input element will be validated.
  • validity: Related to the validity of an input element, it will contain boolean properties.
  • Regarding the validity of the data, there are also nine types of Validity Properties:

    Property Description
    customError If a custom validity message is set and it is set to true.
    patternMismatch If an element’s value does not match its pattern attribute and it is set to true.
    rangeOverflow If an element’s value is greater than it,s max attribute and it is set to true.
    rangeUnderflow If an element’s value is less than its min attribute and it is set to true.
    stepMismatch If an element’s value is invalid per its step attribute and it is set to true.
    tooLong If an element’s value exceeds its maxLength attribute and it is set to true.
    typeMismatch If an element’s value is invalid per its type attribute and it is set to true.
    valid If an element’s value is valid and it is set to true.
    valueMissing If an element (with a required attribute) has no value and it is set to true.


    Last Updated : 03 Oct, 2019
    Like Article
    Save Article
    Previous
    Next
    Share your thoughts in the comments
Similar Reads