JavaScript 3d ago 5 views 4 min read

How to validate form inputs with the Constraint Validation API

Learn to use the native HTML5 Constraint Validation API to check user input before submission. This guide covers the required attributes, JavaScript events, and custom validation logic for modern web forms.

Riya K.
Updated 3h ago
Sponsored

Cloud Hosting — blazing fast websites

Fully managed cloud hosting with free SSL, auto-backups and a friendly cPanel. Built for WordPress, Laravel and custom PHP apps.

Use the native HTML5 Constraint Validation API to enforce input rules before a form submits. You will apply standard attributes like required and pattern, then add custom validation logic using JavaScript events. These steps work on any modern browser that supports the standard validation specification.

Prerequisites

  • A modern web browser (Chrome 10+, Firefox 5+, Safari 5+, Edge 12+).
  • Basic knowledge of HTML form elements and JavaScript.
  • Access to a local development environment or a live web server.

Step 1: Create the HTML form structure

Build a basic HTML form with input fields that need validation. Add the required attribute to fields that must have a value, and use the type="email" attribute to trigger built-in email checking. The browser will automatically show a warning icon next to invalid fields.

<!DOCTYPE html>
<html>
<head>
    <title>Validation Demo</title>
</head>
<body>
    <form id="myForm">
        <label for="username">Username:</label>
        <input type="text" id="username" name="username" required>
        <label for="email">Email:</label>
        input type="email" id="email" name="email" required>
        <label for="password">Password:</label>
        <input type="password" id="password" name="password" required minlength="8">
        <label for="terms">Terms:</label>
        <input type="checkbox" id="terms" name="terms" required>
        <button type="submit">Submit</button>
    </form>
</body>
</html>

You will see the standard browser validation UI appear when you try to submit the form without filling out the required fields. The browser prevents the default submission behavior until all constraints are met.

Step 2: Add the pattern attribute for text formats

Use the pattern attribute to enforce specific text formats like phone numbers or zip codes. The value must be a valid regular expression enclosed in quotes. The browser checks the input against this regex whenever the user changes the field or tries to submit.

<input type="text" id="zip" name="zip" pattern="[0-9]{5}" required>

For example, if a user types "12345", the field is valid. If they type "1234", the browser shows an error message indicating the input does not match the pattern.

Step 3: Implement custom validation logic

Create a custom validation function to handle complex rules that standard attributes cannot cover. Define a function that returns a boolean value: true if the input is valid, false if it is invalid. Assign this function to the setCustomValidity method of the input element.

function validatePassword(input) {
    const password = input.value;
    // Check for uppercase, lowercase, number, and special character
    const hasUpperCase = /[A-Za-z]/.test(password);
    const hasLowerCase = /[a-z]/.test(password);
    const hasNumber = /[0-9]/.test(password);
    const hasSpecial = /[!@#$%^&*(),.?":{}|]/.test(password);
    const length = password.length;

    if (!hasUpperCase || !hasLowerCase || !hasNumber || !hasSpecial || length < 8) {
        input.setCustomValidity('Password must contain uppercase, lowercase, number, special char, and be 8+ chars.');
        return false;
    }
    input.setCustomValidity('');
    return true;
}

Step 4: Connect validation to form events

Attach event listeners to the form and input fields to trigger validation checks. Use the input event to validate as the user types, and the submit event to prevent submission if validation fails. This ensures the user gets immediate feedback without waiting for the form to submit.

const form = document.getElementById('myForm');
const passwordField = document.getElementById('password');

// Validate on input
passwordField.addEventListener('input', function() {
    validatePassword(passwordField);
});

// Prevent submission if invalid
form.addEventListener('submit', function(event) {
    if (!form.checkValidity()) {
        event.preventDefault();
        event.stopPropagation();
    }
    // Form is valid, proceed with submission
    // form.submit();
});

Verify the installation

Open the HTML file in your browser and try to submit the form without filling in the fields. The browser should block the submission and display error messages under each invalid field. Fill in the fields correctly, including a password that meets the custom rules, and the form should submit successfully.

Troubleshooting

Error: "Invalid regular expression" — This happens when the pattern attribute contains a malformed regex. Ensure all special characters in the regex are escaped properly. For example, use pattern="\\d+" for digits instead of pattern="\d+".

Error: "setCustomValidity is not a function" — This indicates the browser does not support the Constraint Validation API. Check that you are using a modern browser like Chrome, Firefox, or Edge. Older browsers like Internet Explorer do not support this API.

Error: Form submits despite invalid input — Ensure you are calling event.preventDefault() inside the submit event listener when checkValidity() returns false. Also, make sure the required attribute is present on fields that must not be empty.

Error: Error message does not appear — The browser may have cached the previous validation state. Clear the browser cache or reload the page to reset the validation state. You can also manually call input.setCustomValidity('') to clear the error state programmatically.

Tip: Use the reportValidity method — This method triggers the validation UI and returns a boolean. Call it before submitting to ensure the user sees any errors immediately.

if (!passwordField.reportValidity()) {
    // Handle invalid state
    console.log('Please fix the password error.');
} else {
    // Proceed with submission
    form.submit();
}
Sponsored

Windows Dedicated Server

High-performance Windows dedicated servers with licensed Windows Server, Remote Desktop access and enterprise-grade hardware.

Tags: JavaScriptFormsHTMLValidation
0
Was this helpful?

Related tutorials

Comments 0

Login to leave a comment.

No comments yet — be the first to share your thoughts.