SimpleTuts.com

Form Validation with JavaScript

1. Introduction

Form validation ensures that the data entered into a form is accurate and complete before it is submitted. JavaScript can be used to validate form inputs on the client side, providing immediate feedback to users.

2. Validating Form Fields

In this tutorial, we will cover how to validate the following form fields:

  • Name: Must contain only letters and spaces.
  • Email: Must be in a valid email format.
  • Phone Number: Must be in a valid format, allowing digits, spaces, parentheses, plus signs, and hyphens.
  • Message: Cannot be empty.

3. Example HTML Form


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Form Validation Example</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            line-height: 1.6;
            margin: 20px;
            max-width: 600px;
        }
        .form-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
        }
        input, textarea {
            width: 100%;
            padding: 8px;
            box-sizing: border-box;
        }
        .error {
            color: red;
            margin-top: 5px;
        }
    </style>
</head>
<body>
    <h1>Contact Form</h1>
    <form id="contactForm">
        <div class="form-group">
            <label for="name">Name:</label>
            <input type="text" id="name" name="name">
            <div class="error" id="nameError"></div>
        </div>

        <div class="form-group">
            <label for="email">Email:</label>
            <input type="email" id="email" name="email">
            <div class="error" id="emailError"></div>
        </div>

        <div class="form-group">
            <label for="phone">Phone Number:</label>
            <input type="text" id="phone" name="phone">
            <div class="error" id="phoneError"></div>
        </div>

        <div class="form-group">
            <label for="message">Message:</label>
            <textarea id="message" name="message" rows="4"></textarea>
            <div class="error" id="messageError"></div>
        </div>

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

    <script>
        document.getElementById('contactForm').addEventListener('submit', function(event) {
            let isValid = true;

            // Clear previous error messages
            document.getElementById('nameError').textContent = '';
            document.getElementById('emailError').textContent = '';
            document.getElementById('phoneError').textContent = '';
            document.getElementById('messageError').textContent = '';

            // Name validation
            const name = document.getElementById('name').value;
            const namePattern = /^[A-Za-z\s]+$/; // Allows letters and spaces only
            if (!namePattern.test(name)) {
                document.getElementById('nameError').textContent = 'Name must contain only letters and spaces.';
                isValid = false;
            }

            // Email validation
            const email = document.getElementById('email').value;
            const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            if (!emailPattern.test(email)) {
                document.getElementById('emailError').textContent = 'Please enter a valid email address.';
                isValid = false;
            }

            // Phone number validation
            const phone = document.getElementById('phone').value;
            const phonePattern = /^[0-9\s()+-]+$/; // Allows digits, spaces, parentheses, plus, and hyphens
            if (!phonePattern.test(phone)) {
                document.getElementById('phoneError').textContent = 'Please enter a valid phone number.';
                isValid = false;
            }

            // Message validation
            const message = document.getElementById('message').value;
            if (message.trim() === '') {
                document.getElementById('messageError').textContent = 'Message cannot be empty.';
                isValid = false;
            }

            // Prevent form submission if validation fails
            if (!isValid) {
                event.preventDefault();
            }
        });
    </script>
</body>
</html>
            
Run Code

4. Explanation of the Validation Script

The JavaScript code included in the example form performs the following actions:

  • Event Listener: Attached to the form's `submit` event to trigger validation.
  • Clear Previous Errors: Clears any existing error messages before validating.
  • Name Validation: Ensures the name contains only letters and spaces using a regular expression.
  • Email Validation: Checks if the email is in a valid format using a regular expression.
  • Phone Number Validation: Validates the phone number format allowing digits, spaces, parentheses, plus signs, and hyphens.
  • Message Validation: Ensures the message field is not empty.
  • Prevent Form Submission: Stops form submission if any validation fails.