Form validation along with example

Certainly! Here's an example of form validation using JavaScript. This example demonstrates basic form validation by checking if the fields are empty.

html
<!DOCTYPE html>
<html>
<head>
<title>Form Validation</title>
<style>
    .error-message {
        color: red;
    }
</style>
</head>
<body>
    <h2>Form Validation</h2>
    <form id="myForm">
        <label for="name">Name:</label>
        <input type="text" id="name" name="name" required><br>
        <span id="nameError" class="error-message"></span><br>

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

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

    <script src="script.js"></script>
</body>
</html>

JavaScript (script.js):
```javascript
document.getElementById("myForm").addEventListener("submit", function(event) {
    event.preventDefault(); // Prevent form submission

    // Get input values
    var name = document.getElementById("name").value;
    var email = document.getElementById("email").value;

    // Reset error messages
    document.getElementById("nameError").textContent = "";
    document.getElementById("emailError").textContent = "";

    // Name validation
    if (name === "") {
        document.getElementById("nameError").textContent = "Name is required";
    }

    // Email validation
    if (email === "") {
        document.getElementById("emailError").textContent = "Email is required";
    } else if (!isValidEmail(email)) {
        document.getElementById("emailError").textContent = "Invalid email format";
    }

    // If there are no errors, proceed with form submission
    if (name !== "" && email !== "" && isValidEmail(email)) {
        // Perform form submission (e.g., send data to server)
        // ...
        // Display success message or redirect to another page
        // ...
        alert("Form submitted successfully!");
    }
});

// Email validation function
function isValidEmail(email) {
    var emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
}

In this example, we have a form with two fields: name and email. The JavaScript code adds an event listener to the form's submit event. When the form is submitted, the event listener function is executed.

Inside the event listener function, we prevent the default form submission using `event.preventDefault()`. Then, we retrieve the values entered in the name and email fields.


Next, we reset the error messages by clearing the content of the error `<span>` elements.

After that, we perform validation for each field. In this example, we check if the fields are empty. If any field is empty, we display an error message in the corresponding error `<span>` element.

For the email field, we also use a regular expression to check for a valid email format. The `isValidEmail()` function tests the email against the regular expression pattern.

Finally, if there are no validation errors (all fields are filled and the email is in a valid format), you can perform the form submission operation, such as sending the form data to a server for further processing. In this example, we display an alert message to indicate a successful form submission.


Note: This is a basic example to demonstrate form validation. In real-world scenarios, you may need to consider more advanced validation techniques, such as checking for specific patterns.


OUTPUT-

img


About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.

We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc





 PreviousNext