Webflow Forms

Custom JS Validation

Overview
Webflow Forms Basics
001
Webflow Forms Limitations & Bugs
002
Basic Form Controls
Form Select
051
Form Textarea
052
Customizing Input Controls
Customizing Radio Buttons & Checkboxes
101
Input Number & Decimal Places
102
Numeric Range Sliders
102
Multi-Select Dropdown
104
Auto-Size Textareas
110
Date Pickers
111
Forms Validation
Forms Validation Basics
200
Input Types
201
Using Regex Patterns in Forms Validation
202
Validating Phone Numbers
202
Custom Validation Errors
203
Custom JS Validation
204
Forms Validation Techniques
Validating Emails
301
Blocking Free Email Provider Addresses
302
Requiring Checkboxes
302
Address Autocomplete
302
Autocomplete / Predictive Input
302
International Phone Numbers
6:50
304
Databinding
Databinding CMS Collections to a Form Select
8:42
401
Forms Validation Techniques
3rd Party Form Handlers
401
Making Forms Dynamic
Displaying Form Parts Conditionally
14:36
501
Multi-Step Forms (MSFs)
501
SPAM Blocking Techniques
Minimizing Form Submission SPAM
600
SPAM Blocking Techniques
CAPTCHA Approaches
601
Form Handlers
3rd Party Form Handlers
901
Integrating the Basin Form Handler
902
Uploading Files
Uploading Files
950
Uploading Files with Uploadcare
951
Uploading Files with Basin
952
No items found.
Published
January 28, 2023
Updated
in lightbox

Here are some notes on Custom JS techniques for advanced forms validation.

Adding Event Listeners for Validation

Use JavaScript to attach event listeners (blur, input, or submit) to the fields or form:

  • blur: Validate when the user leaves a field.
  • input: Validate as the user types.
  • submit: Validate before the form is submitted.
document.querySelector('form').addEventListener('submit', (event) => {
    if (!validateCustomRules()) {
        event.preventDefault(); // Prevent form submission
    }
});

Using Custom Validation Functions

Create custom functions to validate specific rules.

For example:

function validateCustomRules() {
    const inputField = document.querySelector('#username');
    const errorMessage = document.querySelector('#username-error');

    if (inputField.value.length < 5) {
        errorMessage.textContent = 'Username must be at least 5 characters long.';
        inputField.classList.add('invalid');
        return false;
    }

    errorMessage.textContent = '';
    inputField.classList.remove('invalid');
    return true;
}

Leveraging the Constraint Validation API

Modern browsers provide the Constraint Validation API for custom validation while integrating with the native validation system.

Example: Using setCustomValidity

const inputField = document.querySelector('#username');

inputField.addEventListener('input', () => {
    if (inputField.value.length < 5) {
        inputField.setCustomValidity('Username must be at least 5 characters long.');
    } else {
        inputField.setCustomValidity(''); // Clear the error
    }
});

Check Overall Validity

document.querySelector('form').addEventListener('submit', (event) => {
    if (!event.target.checkValidity()) {
        event.preventDefault(); // Prevent submission
    }
});

Real-Time Validation Feedback

Use JavaScript to provide instant feedback using CSS classes.

const inputField = document.querySelector('#username');

inputField.addEventListener('input', () => {
    if (inputField.value.length < 5) {
        inputField.classList.add('invalid');
        inputField.classList.remove('valid');
    } else {
        inputField.classList.add('valid');
        inputField.classList.remove('invalid');
    }
});

CSS for Styling Feedback

input.valid {
    border: 2px solid green;
}
input.invalid {
    border: 2px solid red;
}

Grouping Validation Logic

For forms with multiple fields, create a centralized validation handler.

function validateForm() {
    const usernameField = document.querySelector('#username');
    const passwordField = document.querySelector('#password');

    let isValid = true;

    if (usernameField.value.length < 5) {
        showError(usernameField, 'Username must be at least 5 characters long.');
        isValid = false;
    } else {
        clearError(usernameField);
    }

    if (passwordField.value.length < 8) {
        showError(passwordField, 'Password must be at least 8 characters long.');
        isValid = false;
    } else {
        clearError(passwordField);
    }

    return isValid;
}

function showError(input, message) {
    const error = input.nextElementSibling; // Assume an error span exists
    error.textContent = message;
    input.classList.add('invalid');
}

function clearError(input) {
    const error = input.nextElementSibling; // Assume an error span exists
    error.textContent = '';
    input.classList.remove('invalid');
}

Validation Before Submission

If you prefer validation to occur only when the user submits the form:

document.querySelector('form').addEventListener('submit', (event) => {
    if (!validateForm()) {
        event.preventDefault(); // Prevent submission if validation fails
    }
});

Example: Custom Email Validation

If you need a custom validation beyond type="email", use a regular expression:

function validateEmail(email) {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
}

document.querySelector('#email').addEventListener('blur', (event) => {
    const emailField = event.target;
    if (!validateEmail(emailField.value)) {
        emailField.setCustomValidity('Please enter a valid email address.');
    } else {
        emailField.setCustomValidity('');
    }
});

Best Practices

  1. Use Native Validation When Possible: Combine native HTML5 attributes (required, pattern, etc.) with custom validations.
  2. Graceful Degradation: Ensure the form works with JavaScript disabled (native attributes provide basic validation).
  3. Avoid Inline Scripts: Use external or inline scripts in <script> tags for better maintainability.
  4. Integrate with Accessibility: Use aria-live regions or aria-describedby for informing users about validation messages.

Example Form

<form id="myForm">
    <label for="username">Username:</label>
    <input type="text" id="username" name="username" required>
    <span id="username-error" class="error"></span>

    <label for="password">Password:</label>
    <input type="password" id="password" name="password" required>
    <span id="password-error" class="error"></span>

    <button type="submit">Submit</button>
</form>

With JavaScript, you can extend form validation capabilities while keeping it user-friendly and accessible.

FAQs

Answers to frequently asked questions.

Videos
No items found.
Table of Contents
Comments
Did we just make your life better?
Passion drives our long hours and late nights supporting the Webflow community. Click the button to show your love.