HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

Web Forms API

The Web Forms API provides a set of properties and methods to handle form validation programmatically. While HTML5 attributes (like `required` and `type="email"`) handle basic validation, the Web Forms API allows you to customize error messages and create complex logic using JavaScript.


Validation Lab

Enter a number between 100 and 300 to see the Web Forms API detect different validity states in real-time:

Value Missing
Range Overflow
Range Underflow
Valid

The checkValidity() Method

The checkValidity() method checks if an input element contains valid data. It returns true if the data is valid, and false otherwise.

const input = document.getElementById("myInput");

if (input.checkValidity()) {
    console.log("Input is valid!");
} else {
    console.log(input.validationMessage);
}

Validity Properties

The validity property of an input element returns a ValidityState object. This object contains several boolean properties that tell you exactly *why* an input is invalid:

Property Returns True If...
valueMissing A required field is empty
rangeOverflow Value is greater than max attribute
rangeUnderflow Value is less than min attribute
typeMismatch Data doesn't match type (e.g. invalid email)
valid The input data is completely valid

Custom Validation Messages

You can override the browser's default error message using the setCustomValidity() method. This is perfect for multi-language support or branded error tones.

const pass = document.getElementById("password");

if (pass.value.length < 8) {
    pass.setCustomValidity("Security rule: Password must be 8+ characters!");
} else {
    pass.setCustomValidity(""); // Clear error to allow submittal
}
Important: If you use setCustomValidity() with a non-empty string, the form will never submit until you call it again with an empty string "".

Key Points to Remember

  • The Web Forms API lets you control browser-level validation via JS.
  • checkValidity() is the standard method to trigger a check.
  • The validity object explains the specific reason for failure.
  • validationMessage returns the text the user will see in the popup.
  • setCustomValidity() allows for fully custom error text.