How to validate a form using jQuery?


At first you have to make a html form like.

<html>
<body>
<h2>Validation of a form</h2>
<form id="form" method="post" action="">
First name:<br>
<input type="text" name="firstname" value="john">
<br>
Last name:<br>
<input type="text" name="lastname" value="Doe">
<br>
Email:<br>
<input type="email" name="u_email" value="johndoe@gmail.com">
<br>
<br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

Now use jQuery validation plugin to validate forms' data in easier way.

first,add jQuery library in your file.

<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
then add javascript code:
$(document).ready(function() {
   $("#form").validate();
});
</script>

Then to define rules use simple syntax.

jQuery(document).ready(function() {
   jQuery("#forms).validate({
      rules: {
         firstname: 'required',
         lastname: 'required',
         u_email: {
            required: true,
            email: true,//add an email rule that will ensure the value entered is valid email id.
            maxlength: 255,
         },
      }
   });
});

To define error messages.

messages: {
   firstname: 'This field is required',
   lastname: 'This field is required',
   u_email: 'Enter a valid email',
},

Now finally to submit the form.

submitHandler: function(form) {
   form.submit();
}

Updated on: 09-Sep-2023

29K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements