JavaScript Validation API
- Previous Page Introduction to Web API
- Next Page Web History API
Constraint validation DOM method
Property | Description |
---|---|
checkValidity() | If the input element contains valid data, return true. |
setCustomValidity() | Set the validationMessage attribute of the input element. |
If the input field contains invalid data, display a message:
checkValidity() method
<input id="id1" type="number" min="100" max="300" required> <button onclick="myFunction()">OK</button> <p id="demo"></p> <script> function myFunction() { const inpObj = document.getElementById("id1"); if (!inpObj.checkValidity()) { document.getElementById("demo").innerHTML = inpObj.validationMessage; } } </script>
Constraint validation DOM properties
Property | Description |
---|---|
validity | Contains boolean attributes related to the validity of the input element. |
validationMessage | Contains the message that the browser will display when validity is false. |
willValidate | Indicates whether to validate the input element. |
Validity Attributes
The validity attributes of the input element include many attributes related to data validity:
Property | Description |
---|---|
customError | Set to true if a custom validity message is set. |
patternMismatch | Set to true if the element's value does not match its pattern attribute. |
rangeOverflow | Set to true if the element's value is greater than its max attribute. |
rangeUnderflow | Set to true if the element's value is less than its min attribute. |
stepMismatch | Set to true if the element's value is invalid for its step attribute. |
tooLong | Set to true if the element's value exceeds its maxLength attribute. |
typeMismatch | Set to true if the element's value is invalid for its type attribute. |
valueMissing | Set to true if the element (with the required attribute) does not have a value. |
valid | Set to true if the element's value is valid. |
Example
If the number in the input field is greater than 100 (the input element's max
If the property is set, a message is displayed:
rangeOverflow property
<input id="id1" type="number" max="100"> <button onclick="myFunction()">OK</button> <p id="demo"></p> <script> function myFunction() { let text = "Value OK"; if (document.getElementById("id1").validity.rangeOverflow) { text = "Value too large"; } } </script>
If the number in the input field is less than 100 (the min attribute of the input element) min
If the property is set, a message is displayed:
rangeUnderflow Property
<input id="id1" type="number" min="100"> <button onclick="myFunction()">OK</button> <p id="demo"></p> <script> function myFunction() { let text = "Value OK"; if (document.getElementById("id1").validity.rangeUnderflow) { text = "Value too small"; } } </script>
- Previous Page Introduction to Web API
- Next Page Web History API