JavaScript Validation API
- Previous Page Storage API
- Next Page Web API
Constraints validation DOM methods and properties
Method
Method | Description |
---|---|
checkValidity() | Returns true if the input element contains valid data. |
setCustomValidity() | Sets the validationMessage attribute of the input element. |
Property
Property | Description |
---|---|
validity | Contains boolean attributes related to the validity of the input element. |
validationMessage | Contains the message that the browser will display when the validity is false. |
willValidate | Indicates whether the validation of the input element will be performed. |
Example - checkValidity() method
If the input field contains invalid data, a message will be displayed:
<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>
Validity properties
The input element'sValidity propertiesContains many properties related to data validity:
Property | Description |
---|---|
customError | If a custom validity message is set, set it to true. |
patternMismatch | If the value of the element does not match its pattern attribute, set it to true. |
rangeOverflow | If the value of the element is greater than its max attribute, set it to true. |
rangeUnderflow | If the value of the element is less than its min attribute, set it to true. |
stepMismatch | If the value of the element is invalid according to its step attribute, set it to true. |
tooLong | If the value of the element exceeds its maxLength attribute, set it to true. |
typeMismatch | If the value of the element is invalid according to its type attribute, set it to true. |
valueMissing | If the element (with the required attribute) does not have a value, set it to true. |
valid | If the value of the element is valid, set it to true. |
Example
rangeOverflow property
If the number in the input field is greater than 100 (the max
If the property is set, a message is displayed:
<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>
rangeUnderflow property
If the number in the input field is greater than 100 (the max
If the property is set, a message is displayed:
<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 Storage API
- Next Page Web API