JavaScript form validation

0
697

JavaScript form validation is a technique used to ensure that the data submitted in a form is correct and complete before it is sent to the server. Here's a basic example of how you can implement form validation using JavaScript:

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</title>
    <style>
        .error {
            color: red;
            font-size: 0.875em;
        }
    </style>
</head>
<body>
    <form id="myForm">
        <label for="name">Name:</label>
        <input type="text" id="name" name="name">
        <span class="error" id="nameError"></span><br><br>

        <label for="email">Email:</label>
        <input type="email" id="email" name="email">
        <span class="error" id="emailError"></span><br><br>

        <input type="submit" value="Submit">
    </form>

    <script src="form-validation.js"></script>
</body>
</html>

JavaScript Validation

Create a file named form-validation.js with the following code:

document.getElementById('myForm').addEventListener('submit', function(event) {
    let isValid = true;
    
    // Clear previous errors
    document.getElementById('nameError').textContent = '';
    document.getElementById('emailError').textContent = '';
    
    // Validate Name
    const name = document.getElementById('name').value;
    if (name.trim() === '') {
        document.getElementById('nameError').textContent = 'Name is required';
        isValid = false;
    }
    
    // Validate Email
    const email = document.getElementById('email').value;
    const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailPattern.test(email)) {
        document.getElementById('emailError').textContent = 'Invalid email format';
        isValid = false;
    }
    
    // If form is invalid, prevent submission
    if (!isValid) {
        event.preventDefault();
    }
});

Explanation

  1. HTML Form:

    • Contains fields for name and email.
    • <span> elements are used to display error messages.
  2. JavaScript:

    • Adds an event listener to the form that listens for the submit event.
    • Clears any previous error messages.
    • Validates the name field to ensure it's not empty.
    • Validates the email field using a regular expression pattern to ensure it has the correct format.
    • If validation fails, it prevents the form from being submitted by calling event.preventDefault().

You can expand this example by adding more fields and validations as needed.

Rechercher
Sellect from all Catégories bellow ⇓
Lire la suite
HTML
How To Create a Responsive iFrame In HTML
Advanced usage of HTML <iframe> involves...
Par flowisetech 2025-02-26 13:06:54 0 399
Data Analysis
How Big Data is Transforming Healthcare
Here's a detailed explanation of how Big Data...
Par Nicholas 2025-03-14 08:45:19 0 848
Freelancing/Consulting
Steps to become a freelancer
Becoming a freelancer involves a combination of...
Par Nicholas 2025-01-28 07:38:30 0 879
MySQL
Introduction to SQL (Structured Query Language)
SQL (Structured Query Language) is a...
Par Nicholas 2025-01-25 19:01:47 0 811
Self Development
Self Development: Emotional Intelligence & Relationships
Emotional Intelligence (EI) plays a crucial...
Par flowisetech 2025-02-25 20:25:43 0 379