Santhiya
Santhiya

Reputation: 351

Validating multiple forms using jquery validation

I have nearly 5 forms inside my webpage whose elements are validated using jquery.validate.js. And I have 'save' button(not submit) at the end which on clicking saves all detail. I need to validate all the forms when I click on 'save' and if any validation fails I need to stop that click event.Is there a way to do it?

for example :

<html>
<script type='text/javascript'>
    $(document).ready(function () {
        $('#form1').validate();
        $('#form2').validate();
        $('#form3').validate();
    });
</script>
<form id='form1'>..elements to be validated..</form>
<form id='form2'>..elements to be validated..</form>
<form id='form3'>..elements to be validated..</form>
<form id='form4'>..elements to be validated..</form>...
<input type='button' name='save_btn' id='save_btn' value='save'>
</html>

Also I tried

$("#save_btn").click(function(){
    $("form1").validate();
});

It displays error message but still click function is carried out.If anybody can suggest me some solution it will be more helpful form me.

Thank you.

Upvotes: 1

Views: 1935

Answers (1)

Lawrence Leung
Lawrence Leung

Reputation: 305

you could use the function valid() that is available to check whether a form or a particular element is valid

so you could do something like this for your button click event

$("#save_btn").click(function(){
  if ($("form1").valid()
        && $("form2").valid()
        && $("form3").valid()
        && $("form4").valid())
  {
     // do what you want here
  } else {
     return false; // to suppress the click event
  }
});

Upvotes: 5

Related Questions