Constraint validations

The algorithm that browsers run to determine the validity of a form when it is submitted is called constraint validation. To constrain data or check validity, the algorithm utilizes new HTML5 attributes such as min, max, step, pattern, and required, as well as existing attributes such as maxlength and type.

In HTML5, basic constraints are declared in two different ways:

  • By choosing the most semantically appropriate value for the type attribute of the <input> element
  • By setting values on validation-related attributes and allowing basic constraints to be described in a simple way without the need for JavaScript

HTML5 constraint validation APIs

Nowadays, an increasing number of browsers are supporting the constraint validation API, and it's becoming more and more reliable. However, HTML5 constraint validation doesn't remove the need for validation on the server side.

At a high level, this API covers the following features:

  • Form fields have a validity property
  • Form fields also have a generic checkValidity() method
  • Finally, there is a setCustomValidity() method

The validity object

The validity object is a set of keys and Boolean values that represent the validity of a particular form. In simple terms, we can say that it tells what a particular form lacks.

Let us take the numeric field type as an example to understand this. With the numeric field type, we can specify that a form field should be numeric and we can set the limitation; for example, the number should be higher than 0 and less than 25. The validity property would actually be able to tell you if the value wasn't a number or was too low or too high.

The validity object of a DOM node returns a ValidityState object containing a number of Boolean properties related to the validity of the data in the node. In a ValidityState object, whenever we get a reference to it, we can keep a hold of it, and the validity checks that we get in return will update as needed when the changes occur as shown in the following code example:

<head>
<script>
  function validateInput(){
    var bool1= document.getElementById('handbook1').validity.customError;
    var result1=document.getElementById('result1').innerHTML = bool1;
  }
</script>
</head>
<body>
  <input type= "text" id="handbook1">
  <div>
  <label>Result1:</label><output id="result1" ></output>
  </div>
  <input type="button" value="Validate" onclick="validateInput()">
</body>

The checkValidity method

The checkValidity method is called to check for the value that this method returns for the successful and unsuccessful validation scenarios. It returns a Boolean value, and we can use this method when there is no need to know why a field is invalid, or we can use this method before we sneak into the validity property to know why the field is not valid.

This method allows us to check validation on the form without any input from the user.

Validation of form is checked whenever the user or the script code submits the form, but this method allows validation to be done at any time, as shown in the following code example:

<head>
<script>
  function validateInput(){
    //false
    var bool2=document.getElementById('handbook2').checkValidity(); //true
    var result1=document.getElementById('result1').innerHTML = bool1;
    var result2=document.getElementById('result2').innerHTML = bool2;
  }
</script>
</head>
<body>
  <input type= "text" id="handbook1" required>
  <input type= "text" id="handbook2" value="handbook">
  <div>
  <label>Result1:</label><output id="result1"></output>
  </div>
  <div>
  <label>Result2:</label><output id="result2"></output>
  </div>
  <input type="button" value="Validate" onclick="validateInput()">
</body>

The output of the preceding code will be as shown in the following screenshot:

The checkValidity method

The setCustomValidity() method

The setCustomValidity() method lets us decide logically and create a custom validation error message and display it when an invalid input is submitted to the form. This lets us use JavaScript code to establish a validation failure other than those offered by the standard constraint validation APIs. The message is displayed while reporting the problem.

This method also allows us to set a message and sets the field as being in an error state by default. If the argument is the empty string, the custom error is cleared or is considered valid. When we do not customize the error message using the setCustomValidity()method, the built-in error message is displayed, as shown in the following code example:

<script>
  function check(input){
    if (input.value != document.getElementById('email_addr').value) {
      input.setCustomValidity('Both the email addresses must match.'),
    }
    else{
      input.setCustomValidity(''),
    }
  }
</script>
<body>
  <form id="myForm">
  <div>
  <label>Enter Email Address:</label>
  <input type="email" id="email_addr" name="email_addr">
  </div>
  <div>
  <label>Repeat Email Address:</label>
  <input type="email" id="email_addr_repeat" name="email_addr_repeat">
  </div>
  <input type="submit" value="Validate" onclick="check(this)">
</form>

The output of the preceding code will be as shown in the following screenshot:

The setCustomValidity() method

The willValidate attribute

The willValidate attribute indicates whether an element will be validated based on the form's validation rules and constraints. If any of the constraints, such as the required attribute or the pattern attribute, are set on the control, the willValidate field will let you know that validation checking will be enforced.

This attribute returns true if the element will be validated when the form is submitted; otherwise, it will return false, as shown in the following code example:

<script>
  function validateInput(){
    var bool1= document.getElementById('handbook1').willValidate; //true
    var bool2=document.getElementById('handbook2').willValidate; //undefined
    var bool3= document.getElementById('handbook3').willValidate; //false
    var result1=document.getElementById('result1').innerHTML = bool1;
    var result2=document.getElementById('result2').innerHTML = bool2;
    var result3=document.getElementById('result3').innerHTML = bool3;
  }
</script>
<body>
  <input type= "text" id="handbook1" required value= "handbook">
  <div id= "handbook2" type="text">
  <input type= "text" id="handbook3" disabled>
  <div>
  <label>Result1:</label><output id="result1" ></output>
  </div>
  <div>
  <label>Result2:</label><output id="result2" ></output>
  </div>
  <div>
  <label>Result3:</label><output id="result3" ></output>
  </div>
  <input type="button" value="Validate" onclick="validateInput()">
</body>

The output of the preceding code will be as shown in the following screenshot:

The willValidate attribute

The validationMessage attribute

The validationMessage attribute allows us to programmatically query a localized error message that the control does not satisfy. If the control is not a candidate for constraint validation, or if the element's value satisfies its constraints, validationMessage sets to an empty string.

For instance, if a required field has no input, the browser will present its default error message to the user. Once supported, this is the text string that will be returned by the validationMessage field as shown in the following code example:

<script>
  function validateInput(){
    var bool1= document.getElementById('handbook1').validationMessage;
    var bool2=document.getElementById('handbook2').validationMessage;
    var result1=document.getElementById('result1').innerHTML = bool1;
    var result2=document.getElementById('result2').innerHTML = bool2;
  }
</script>
<body>
  <input type= "text" id="handbook1" required/>
  <input type= "text" id="handbook2" value= "handbook">
  <div>
  <label>Result1:</label><output id="result1" ></output>
  </div>
  <div>
  <label>Result2:</label><output id="result2" ></output>
  </div>
  <input type="button" value="Validate" onclick="validateInput()">
</body>

The output of the preceding code will look as shown in the following screenshot:

The validationMessage attribute

HTML5 provides us with several ways to enforce correctness on forms; that is, HTML5 provides several validity constraints on any given <form> control.

As mentioned previously, several validity constraints on any given <form> control are discussed in this section.

The patternMismatch property

The patternMismatch property is used to set any pattern rule on a <form> control and returns if the <input> value matches the rules defined by the pattern attribute.

The validity.patternMismatch attribute

  • If the element's value does not match the provided pattern attribute, it returns true; otherwise, it returns false
  • The element will match the :invalid CSS pseudo-class when it returns true as shown in the following code example:
    <script>
      function validateInput(){
        var bool1= document.getElementById('handbook1').validity.patternMismatch; //false
        var bool2= document.getElementById('handbook2').validity.patternMismatch; //true
        var result1=document.getElementById('result1').innerHTML = bool1;
        var result2=document.getElementById('result2').innerHTML = bool2;
      }
    </script>
    <body>
      <input type= "text" id="handbook1" pattern="[0-9]{5}"  value="123456">
      <input type= "text" id="handbook2" pattern="[a-z]{3}"  value="xyz">
      <div>
      <label>Result1:</label>	<output id="result1"></output>
      </div>
      <div>
      <label>Result2:</label>	<output id="result2"></output>
      </div>
      <input type="button" value="Validate" onclick="validateInput()">
    </body>

    The output of the preceding code will be as shown in the following screenshot:

    The validity.patternMismatch attribute

The customError property

The customError property is used to handle the errors that are calculated and set by the application code. This property validates whether the customized error message is set or not.

It is used to call the setCustomValidity() property to put a form control into the customError state.

The validity.customError property

If the element has a custom error, it returns true; otherwise, it returns false, as shown in the following code example:

<script>
  function validateInput(){
    Var bool1=document.getElementById('handbook1').validity.customError; //false
    var bool2= document.getElementById('handbook2').setCustomValidity('Invalid Message'),
    var bool3= document.getElementById('handbook2').validity.customError; //true
    var result1=document.getElementById('result1').innerHTML = bool1;
    var result2=document.getElementById('result2').innerHTML = bool2;
    var result3=document.getElementById('result3').innerHTML = bool3;
  }
</script>
<body>
  <input type= "text" id="handbook1">
  <input type= "text" id="handbook2">
  <div>
  <label>Result1:</label>  <output id="result1" ></output>
  </div>
  <div>
  <label>Result2:</label>  <output id="result2" ></output>
  </div>
  <div>
  <label>Result3:</label>  <output id="result3" ></output>
  </div>
  <input type="button" value="Validate" onclick="validateInput()">
</body>

The output of the preceding code will be as shown in the following screenshot:

The validity.customError property

The rangeOverflow property

The rangeOverflow property is used to notify that the input value of the <form> control is greater than the maximum value or that the input value is out of range.

This property checks the max attribute to a <form> control with the maximum input value.

The validity.rangeOverflow property

  • If the element's value is higher than the provided maximum value, it returns true; otherwise, it returns false
  • The element will match the :invalid and :out-of-range CSS pseudo-classes when it returns true, as shown in the following code example:
    <script>
      function validateInput(){
        var bool1= document.getElementById('handbook1').validity.rangeOverflow; //false
        var bool2=document.getElementById('handbook2').validity.rangeOverflow; //true
        var result1=document.getElementById('result1').innerHTML = bool1;
        var result2=document.getElementById('result2').innerHTML = bool2;
      }
    </script>
    <body>
      <input type= "number" id="handbook1" max="3" value="1">
      <input type= "number" id="handbook2" max="3" value="4">
      <div>
      <label>Result1:</label>  <output id="result1" ></output>
      </div>
      <div>
      <label>Result2:</label>  <output id="result2" ></output>
      </div>
      <input type="button" value="Validate" onclick="validateInput()">
    </body>

    The output of the preceding code will be as shown inthe following screenshot:

    The validity.rangeOverflow property

The rangeUnderflow property

The rangeUnderflow property is used to notify that the input value of the <form> control is lower than the minimum value.

This property checks the min attribute to a <form> control with the minimum input value.

The validity.rangeUnderflow property

  • If the element's value is lower than the provided minimum value, it returns true; otherwise, it returns false
  • The element will match the :invalid and :out-of-range CSS pseudo-classes when it returns true, as shown in the following code example:
    <script>
      function validateInput(){
        var bool1= document.getElementById('handbook1').validity.rangeUnderflow; //true
        var bool2= document.getElementById('handbook2').validity.rangeUnderflow; //false
        var result1=document.getElementById('result1').innerHTML = bool1;
        var result2=document.getElementById('result2').innerHTML = bool2;
      }
    </script>
    <body>
      <input type= "number" id="handbook1" min="3" value="1">
      <input type= "number" id="handbook2" min="3" value="4">
      <div>
      <label>Result1:</label>  <output id="result1" ></output>
      </div>
      <div>
      <label>Result2:</label>  <output id="result2" ></output>
      </div>
      <input type="button" value="Validate" onclick="validateInput()">
    </body>

    The output of the preceding code will look as shown in the following screenshot:

    The validity.rangeUnderflow property

The stepMismatch property

The stepMismatch property ensures that an <input> value complies with the rules or standards of the values of min, max, and step. For example, if the step value is five and the value entered is three, we will have a step mismatch in this case.

The validity.stepMismatch property

  • If the element's value doesn't fit the rules given by the step attribute, it returns true; otherwise, it returns false
  • The element will match the :invalid and :out-of-range CSS pseudo-classes when it returns true, as shown in the following code example:
    <script>
      function validateInput(){
        var bool1= document.getElementById('handbook1').validity.stepMismatch; //true
        var bool2= document.getElementById('handbook2').validity.stepMismatch; //false
        var result1=document.getElementById('result1').innerHTML = bool1;
        var result2=document.getElementById('result2').innerHTML = bool2;
      }
    </script>
    <body>
      <input type= "number" id="handbook1" step="3" value="1">
      <input type= "number" id="handbook2" step="3" value="6">
      <div>
      <label>Result1:</label>  <output id="result1" ></output>
      </div>
      <div>
      <label>Result2:</label>  <output id="result2" ></output>
      </div>
      <input type="button" value="Validate" onclick="validateInput()">
    </body>

    The output of the preceding code will be as shown in the following screenshot:

    The validity.stepMismatch property

The tooLong property

This property ensures that an <input> field does not contain too many characters.

We ensure this by adding a maxlength attribute on the <form> control.

The validity.tooLong property

  • If the element's value is longer than the provided maximum length, it returns true; otherwise, it returns false
  • The element will match the :invalid and :out-of-range CSS pseudo-classes when it returns true, as shown in the following code example:
    <script>
      function validateInput(){
        var bool1=  document.getElementById('handbook1').validity.tooLong; //false
        var bool2=    document.getElementById('handbook2').validity.tooLong; //true
        var result1=document.getElementById('result1').innerHTML = bool1;
        var result2=document.getElementById('result2').innerHTML = bool2;
        }
    </script>
    <body>
      <input type="text" id="handbook1" maxlength="5" value="12345678"/>
      <input type="text" id="handbook2" maxlength="5" value="xyz"/>
      <div>
      <label>Result1:</label>  <output id="result1" ></output>
      </div>
      <div>
      <label>Result2:</label>  <output id="result2" ></output>
      </div>
      <input type="button" value="Validate" onclick="validateInput()">
    </body>

    The output of the preceding code will be as shown in the following screenshot:

    The validity.tooLong property

The typeMismatch property

The typeMismatch property is used to notify that the <input> value does not match with the <form> control in cases such as e-mail, URL, and number, and ensures that the type of value matches its expected field.

The validity.typeMismatch property

  • If the element's value is not in the correct syntax, it returns true; otherwise, it returns false
  • The element will match the :invalid CSS pseudo-class when it returns true, as shown in the following code example:
    <script>
      function validateInput(){
        var bool1= document.getElementById('handbook1').validity.typeMismatch; //false
        var bool2= document.getElementById('handbook2').validity.typeMismatch; //true
        var result1=document.getElementById('result1').innerHTML = bool1;
        var result2=document.getElementById('result2').innerHTML = bool2;
      }
    </script>
    <body>
      <input type="email" id="handbook1" value="[email protected]">
      <input type="email" id="handbook2" value="handbook">
      <div>
      <label>Result1:</label>  <output id="result1" ></output>
      </div>
      <div>
      <label>Result2:</label>  <output id="result2" ></output>
      </div>
      <input type="button" value="Validate" onclick="validateInput()">
    </body>

    The output of the preceding code will be as shown in the following screenshot:

    The validity.typeMismatch property

The valueMissing property

The valueMissing property ensures that some value is set on the <form> control. To ensure this, set the required attribute on the <form> control to true.

The validity.valueMissing property

  • If the element has no value but is a required field, it returns true; otherwise, it returns false
  • The element will match the :invalid CSS pseudo-class when it returns true, as shown in the following code example:
    <script>
      function validateInput(){
        var bool1=document.getElementById('handbook1').validity.valueMissing; //false
        var bool2= document.getElementById('handbook2').validity.valueMissing; //true
        var result1=document.getElementById('result1').innerHTML = bool1;
        var result2=document.getElementById('result2').innerHTML = bool2;
      }
    </script>
    <body>
      <input type= "text" id="handbook1" required value="handbook">
      <input type= "text" id="handbook2" required value="">
      <div>
      <label>Result1:</label>  <output id="result1" ></output>
      </div>
      <div>
      <label>Result2:</label>  <output id="result2" ></output>
      </div>
      <input type="button" value="Validate" onclick="validateInput()">
    </body>

The output of the preceding code will look as shown in the following screenshot:

The validity.valueMissing property

The valid property

The valid property is used to check whether the field is valid.

The validity.valid property

  • If the element's value has no validity problems, it returns true; otherwise, it returns false
  • The element will match the :invalid CSS pseudo-class when it returns true, as shown in the following code example:
    <script>
      function validateInput(){
        var bool1= document.getElementById('handbook1').validity.valid; //true
        var bool2= document.getElementById('handbook2').validity.valid; //false
        var result1=document.getElementById('result1').innerHTML = bool1;
        var result2=document.getElementById('result2').innerHTML = bool2;;
      }
    </script>
    <body>
      <input type= "text" id="handbook1" required value="handbook">
      <input type= "text" id="handbook2" required value="">
      <div>
      <label>Result1:</label>  <output id="result1" ></output>
      </div>
      <div>
      <label>Result2:</label>  <output id="result2" ></output>
      </div>
      <input type="button" value="Validate" onclick="validateInput()">
    </body>

    The output of the preceding code will be as shown in the following screenshot:

    The validity.valid property

The following table shows the various attributes with their possible values and associated violations:

Attribute

<Input> types supporting the attribute

Possible values

Constraint description

Associated violation

required

date, month, week, checkbox, radio button, URL, telephone, e-mail, text, password, search, time, range, number and tags such as <select>, <textarea>, checkbox, and radiobutton

It returns the Boolean value None; when present, it returns true and when absent, it returns false

The value is to be filled mandatorily

Constraint violation:

Missing

min

number and range

Must be a valid number

The filled parameter must be greater than or equal to the value defined

Constraint violation:

Underflow

month, date, and week

Must be a valid date

datetime-local, time, and datetime

Must be a valid date and time

maxlength

tags such as <textarea> and attributes are text, password, search, tel, url, and email

Must be an integer length

The value of the attribute must not be greater than the number of characters filled

Constraint violation:

Too long

max

number and range

Must be a valid number

The filled parameter must be lesser than or equal to the value defined

Constraint violation: Overflow

month ,date, and week

Must be a valid date

datetime-local, time, and datetime

Must be a valid date and time

pattern

text, search, URL, telephone, e-mail, and password

It is a regular expression defined using JavaScript

The value of the attribute must exactly match the pattern defined

Constraint violation: Pattern mismatch

step

month

Must be an integer number of months

Until the value of step is set to the any literal (values available in the step menu), value will be min value plus an integral multiple of step

Constraint violation: Step mismatch

date

Must be an integer number of days

week

Must be an integer number of weeks

datetime, datetime-local, and time

Must be an integer number of seconds

number and range

Must be an integer

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.200.76