Web Validation API

Validate form inputs with built-in browser features

✅ What is the Validation API?

The Web Validation API helps you check if form inputs are valid without writing complex validation code. It's built into modern browsers and works with HTML5 form validation.


// Check if an input is valid
const emailInput = document.getElementById('email');
console.log("Is valid:", emailInput.checkValidity());
console.log("Error message:", emailInput.validationMessage);
                                    

Output:

Is valid: false

Error message: Please include an '@' in the email address.

Validation Methods

✔️

checkValidity()

Returns true if input is valid

input.checkValidity()
📝

validationMessage

Gets the error message

input.validationMessage
🎯

setCustomValidity()

Set custom error messages

input.setCustomValidity("Error!")
📊

validity

Detailed validation state

input.validity.valueMissing

🔹 Basic Form Validation

Here's a simple example of form validation:

<form id="myForm">
    <input type="email" id="email" required placeholder="Enter email">
    <input type="password" id="password" required minlength="6" placeholder="Password">
    <button type="submit">Submit</button>
</form>

<script>
document.getElementById('myForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const email = document.getElementById('email');
    const password = document.getElementById('password');
    
    // Check if form is valid
    if (email.checkValidity() && password.checkValidity()) {
        alert('Form is valid!');
    } else {
        // Show error messages
        if (!email.checkValidity()) {
            alert('Email error: ' + email.validationMessage);
        }
        if (!password.checkValidity()) {
            alert('Password error: ' + password.validationMessage);
        }
    }
});
</script>

Interactive Example:



🔹 Custom Validation Messages

You can create custom error messages for better user experience:

// Custom validation for password confirmation
function validatePasswordConfirm() {
    const password = document.getElementById('password');
    const confirmPassword = document.getElementById('confirmPassword');
    
    if (password.value !== confirmPassword.value) {
        confirmPassword.setCustomValidity('Passwords do not match');
    } else {
        confirmPassword.setCustomValidity(''); // Clear error
    }
}

// Custom validation for age
function validateAge() {
    const ageInput = document.getElementById('age');
    const age = parseInt(ageInput.value);
    
    if (age < 18) {
        ageInput.setCustomValidity('You must be at least 18 years old');
    } else if (age > 120) {
        ageInput.setCustomValidity('Please enter a valid age');
    } else {
        ageInput.setCustomValidity(''); // Valid
    }
}

Example Usage:

Custom messages provide clearer feedback to users

✅ "Passwords do not match" instead of generic error

✅ "You must be at least 18 years old" for age validation

🔹 Validity States

The validity property provides detailed information about validation errors:

function checkInputValidity(input) {
    const validity = input.validity;
    
    if (validity.valueMissing) {
        console.log('Field is required but empty');
    }
    
    if (validity.typeMismatch) {
        console.log('Value does not match expected type');
    }
    
    if (validity.tooShort) {
        console.log('Value is too short');
    }
    
    if (validity.tooLong) {
        console.log('Value is too long');
    }
    
    if (validity.patternMismatch) {
        console.log('Value does not match pattern');
    }
    
    if (validity.valid) {
        console.log('Input is valid!');
    }
}

Validity Properties:

  • valueMissing: Required field is empty
  • typeMismatch: Wrong input type (e.g., text in email field)
  • tooShort/tooLong: Length validation
  • patternMismatch: Doesn't match regex pattern

🔹 Real-Time Validation

Validate inputs as the user types:

<input type="email" id="emailInput" placeholder="Enter email">
<div id="emailError" style="color: red;"></div>

<script>
const emailInput = document.getElementById('emailInput');
const emailError = document.getElementById('emailError');

emailInput.addEventListener('input', function() {
    if (this.value === '') {
        emailError.textContent = '';
        return;
    }
    
    if (this.checkValidity()) {
        emailError.textContent = '';
        this.style.borderColor = 'green';
    } else {
        emailError.textContent = this.validationMessage;
        this.style.borderColor = 'red';
    }
});
</script>

Live Validation Demo:

Error messages appear here as you type

🧠 Test Your Knowledge

Which method checks if an input is valid?