How To Validate Form Before Submit In Jquery

Form validation is an essential part of any web application. It helps in ensuring that the user is providing all the required information in the correct format before submitting the form. In this blog post, we will learn how to validate a form using jQuery before it gets submitted to the server.

Step 1: Include jQuery Library

First of all, include the jQuery library in your project. You can either download it from jQuery’s official website or use the CDN link provided below:

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

Step 2: Create an HTML Form

Create an HTML form containing some input fields that need to be validated. For example, create a simple registration form with name, email, and password fields.

<form id="registrationForm">
    <label for="name">Name:</label>
    <input type="text" id="name" name="name">
    <br>

    <label for="email">Email:</label>
    <input type="email" id="email" name="email">
    <br>

    <label for="password">Password:</label>
    <input type="password" id="password" name="password">
    <br>

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

Step 3: Write the jQuery Validation Script

Now, let’s write the jQuery script to validate the form fields before submitting. Attach a submit event handler to the form and use the preventDefault() method to prevent the form from submitting if the validation fails.

<script>
$(document).ready(function () {
    $('#registrationForm').on('submit', function (e) {
        // Prevent form submission
        e.preventDefault();

        // Validate form fields
        if (validateForm()) {
            // If validation passes, submit the form
            this.submit();
        }
    });
});

Next, create a validateForm() function to perform the actual validation. Check if the input fields are empty or if the email address is not in a valid format. Display an error message if the validation fails and return false. Otherwise, return true.

function validateForm() {
    // Get input field values
    var name = $('#name').val();
    var email = $('#email').val();
    var password = $('#password').val();

    // Validate fields
    if (name === '' || email === '' || password === '') {
        alert('All fields are required.');
        return false;
    }

    // Validate email format
    var emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
    if (!emailRegex.test(email)) {
        alert('Please enter a valid email address.');
        return false;
    }

    // If validation passes
    return true;
}

Conclusion

In conclusion, jQuery makes it easy to validate form input fields before submitting them. Just follow the steps above to create a simple validation script for any form. Remember to always perform server-side validation as well, as client-side validation can be bypassed.