简体   繁体   中英

jQuery Validate: Validating multiple forms on single page if has same value

Example if I have multiple forms, how I can validate the "identity_passport" must be different cannot be the same:

<form id="form_1">
  <input name="name_1">
  <input name="email_1">
  <input name="identity_passport_1" data-field="identity_passport">
</form>

<form id="form_2">
  <input name="name_2">
  <input name="email_2">
  <input name="identity_passport_2" data-field="identity_passport">
</form>

<form id="form_3">
  <input name="name_3">
  <input name="email_3">
  <input name="identity_passport_3" data-field="identity_passport">
</form>

<button type="submit" id="button_submit">Submit</button>

I have custom submit button that place outside of the form in a single page. I am using .each() method like (below):

<script>
  $('form').each(function () {

    $(this).validate({
      errorElement: "span",
      errorPlacement: function (error, element) {
        //
      },
      success: function (label, element) {
        //
      },
      highlight: function (element, errorClass, validClass) {
        //
      }
    });

  });
</script>

UPDATE 2018/01/25: After a long try, is possible. Here is my test and demo: https://jsfiddle.net/claudchan/4t41kjLr/4/

Example if I have multiple forms, how I can validate the "identity_passport" must be different...

It is not possible using jQuery Validate to simultaneously validate fields across different form containers.

The jQuery Validate plugin evaluates a single form at a time using its rules and settings. It cannot evaluate any fields contained within another completely separate form. Nor can it evaluate fields from different forms against each other.


Workaround: use a single form container and dynamically add your fields . As long as you maintain unique name attributes, it will work.

There is a jquery plugin is available to validate the form and you can also validate your form without it. you just have to keep in mind is that each keyword will trigger only one form.

Don't use ID if you have multiple forms with for same task it will give you an HTML DOM error. Instead of that use the class name to validate.

$('form').each(function() {   // <- selects every <form> on page
    $(this).validate({        // <- initialize validate() on each form
        // your options       // <- set your options inside
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM