JavaScript form validation

0
692

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
PHP
How to Build a Clean Online Portfolio Using PHP
Building a clean online portfolio requires...
Par flowisetech 2025-02-25 21:15:02 0 402
HTML
Introduction To HTML
HTML (HyperText Markup Language) is the...
Par Nicholas 2025-01-13 12:52:35 0 938
E-commerce and Digital Marketing
How to Make Money Through E-commerce & Selling Products
Here’s a comprehensive guide on how to...
Par flowisetech 2025-02-17 20:51:35 0 394
Business
Steps On How To Start a Business Without a Physical Shop or a Website
Starting a business without a physical shop or...
Par flowisetech 2025-02-24 08:45:03 0 306
Self Development
How Build a mindset for wealth
Building a mindset for wealth requires...
Par flowisetech 2025-02-16 15:40:07 0 391