JavaScript Form Validation

Learn how to validate user input with JavaScript to create robust and user-friendly web forms.

Introduction to Form Validation

Form validation is a crucial aspect of web development that ensures users enter information correctly before it's submitted to a server. JavaScript provides powerful tools to validate user input in real-time, enhancing user experience and data integrity.

Key benefits of JavaScript validation:
  • Immediate feedback to users
  • Reduced server load by catching errors client-side
  • Improved data quality and accuracy
  • Enhanced user experience with real-time validation
  • Custom validation rules beyond HTML5 capabilities

Example 1: Required Field Validation

Ensure critical form fields are completed before submission. This example demonstrates how to check for empty fields and provide user feedback.

// Required Field Validation
function validateRequiredField(fieldId, errorId) {
    const field = document.getElementById(fieldId);
    const error = document.getElementById(errorId);
    
    if (field.value.trim() === '') {
        error.style.display = 'block';
        field.style.borderColor = 'var(--error)';
        return false;
    } else {
        error.style.display = 'none';
        field.style.borderColor = 'var(--success)';
        return true;
    }
}

// Form submission handler
document.getElementById('requiredForm').addEventListener('submit', function(e) {
    e.preventDefault();
    const isValid = validateRequiredField('username', 'usernameError');
    
    if (isValid) {
        document.getElementById('requiredSuccess').style.display = 'block';
        this.reset();
    }
});

Required Field Demo

Username is required
Form submitted successfully!

Example 2: Email Validation

Validate email addresses using regular expressions to ensure they match the proper format.

// Email Validation
function validateEmail() {
    const emailInput = document.getElementById('email');
    const emailError = document.getElementById('emailError');
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    
    if (!emailRegex.test(emailInput.value)) {
        emailError.style.display = 'block';
        emailInput.style.borderColor = 'var(--error)';
        return false;
    } else {
        emailError.style.display = 'none';
        emailInput.style.borderColor = 'var(--success)';
        return true;
    }
}

// Form submission handler
document.getElementById('emailForm').addEventListener('submit', function(e) {
    e.preventDefault();
    const isValid = validateEmail();
    
    if (isValid) {
        document.getElementById('emailSuccess').style.display = 'block';
        this.reset();
    }
});

Email Validation Demo

Please enter a valid email address
Email submitted successfully!

Example 3: Selection Validation

Validate which item is selected by the user from a dropdown list.

// Selection Validation
function validateSelection() {
    const select = document.getElementById('selection');
    const selectionError = document.getElementById('selectionError');
    const successMsg = document.getElementById('selectionSuccess');
    
    if (select.value === "") {
        selectionError.style.display = 'block';
        successMsg.style.display = 'none';
        return false;
    } else {
        selectionError.style.display = 'none';
        successMsg.style.display = 'block';
        successMsg.innerHTML = `Selected: ${select.options[select.selectedIndex].text}`;
        return true;
    }
}

// Initialize with default value
document.getElementById('selection').addEventListener('change', validateSelection);

Selection Validation Demo

Please select an item

More Validation Examples

Explore more JavaScript validation techniques:

Password Validation

Validate password strength and matching

View Example

Date Validation

Validate date formats and ranges

View Example

Phone Validation

Validate international phone numbers

View Example

Credit Card Validation

Validate credit card numbers and types

View Example