How to validate form before submit in jquery

You can validate a form before submitting it in jQuery using the submit() method. The submit() method is triggered when the form is submitted, and it can be used to perform form validation. If the validation fails, the form submission can be prevented using the preventDefault() method.

How to validate form before submit

Here’s an example:
$(document).ready(function() {

  $("form").submit(function(event) {

    var formIsValid = true;

    // Get all the input elements in the form
    var inputs = $(this).find("input");

    // Loop through each input and check if it's valid
    inputs.each(function() {
      var input = $(this);

      // Check if the input is empty
      if (input.val() === "") {
        formIsValid = false;
        input.addClass("error");
      } else {
        input.removeClass("error");
      }
    });

    // If the form is not valid, prevent the form submission
    if (!formIsValid) {
      event.preventDefault();
    }
  });
});

In the example above, the submit() method is used to perform form validation when the form is submitted. The preventDefault() method is used to prevent the form submission if the validation fails. The formIsValid variable is used to track the validation state of the form.

The inputs variable is used to store all the input elements in the form, and the each() method is used to loop through each input and check if it’s valid. If an input is empty, the formIsValid variable is set to false, and an “error” class is added to the input using the addClass() method. If the input is not empty, the “error” class is removed using the removeClass() method. The final check for formIsValid prevents the form submission if the validation fails.

Leave a Reply

Your email address will not be published. Required fields are marked *