Client-Side Form Validation with JavaScript

Client-side validation gives users instant feedback before a form ever hits the server — genuinely better UX, though it should always be paired with real server-side validation, never trusted alone.

const form = document.querySelector('#signup-form');

form.addEventListener('submit', (e) => {
    const errors = [];
    const email = form.email.value;
    const password = form.password.value;

    if (!/^[\w.+-]+@[\w-]+\.\w+$/.test(email)) {
        errors.push('Please enter a valid email address');
    }
    if (password.length < 8) {
        errors.push('Password must be at least 8 characters');
    }

    if (errors.length > 0) {
        e.preventDefault(); // stop the actual form submission
        showErrors(errors);
    }
});

Don’t Forget Native HTML Validation

<input type="email" required>
<input type="password" minlength="8" required>
<input type="number" min="0" max="120">

Native HTML validation attributes handle a surprising amount for free, work without any JavaScript at all, and are naturally accessible to screen readers — use them as the first layer, with JavaScript validation for anything more complex layered on top.