JavaScript Validation API Overview
The JavaScript Constraint Validation API provides DOM methods and properties to validate user input. Here's a breakdown of some key methods and properties:
Key Methods
- checkValidity(): Returns true if an input element contains valid data.
- setCustomValidity(): Assigns a custom validation message to an input element, which will be used by the browser when the input's validity is false.
When an input field contains invalid data, the following example demonstrates how to display a message using checkValidity():
<input id="input1" type="number" min="100" max="300" required>
<button onclick="validateInput()">OK</button>
<p id="message"></p>
<script>
function validateInput() {
const inputElement = document.getElementById("input1");
if (!inputElement.checkValidity()) {
document.getElementById("message").innerHTML = inputElement.validationMessage;
}
}
</script>
Key Properties
- validity: Contains boolean properties reflecting the validity state of an input element.
- validationMessage: Stores the message that the browser displays when the input's validity is false.
- willValidate: Indicates whether an input element will undergo validation.
Validity State Properties
The validity property includes several sub-properties indicating specific validation errors:
- customError: True if a custom validity message has been set.
- patternMismatch: True if the input value does not match its pattern attribute.
- rangeOverflow: True if the input value exceeds its maximum value.
- rangeUnderflow: True if the input value is below its minimum value.
- stepMismatch: True if the input value does not fit the step interval.
- tooLong: True if the input value exceeds its maximum length.
- typeMismatch: True if the input value is not of the correct type.
- valueMissing: True if a required input is empty.
- valid: True if the input passes all validation checks.
Example Use Cases
Case: Display a message when the input number exceeds the maximum value
<input id="input1" type="number" max="100">
<button onclick="validateRange()">OK</button>
<p id="message"></p>
<script>
function validateRange() {
let message = "Value OK";
if (document.getElementById("input1").validity.rangeOverflow) {
message = "Value too large";
}
document.getElementById("message").innerText = message;
}
</script>
Case: Display a message when the input number is less than the minimum value
<input id="input1" type="number" min="100">
<button onclick="validateRange()">OK</button>
<p id="message"></p>
<script>
function validateRange() {
let message = "Value OK";
if (document.getElementById("input1").validity.rangeUnderflow) {
message = "Value too small";
}
document.getElementById("message").innerText = message;
}
</script>