简体   繁体   English

一个页面上的jquery.validator和两个联系表单将在提交时验证空的一个

[英]jquery.validator and two contact forms on one page will validate empty one on submit

I currently have two of the same contact forms being used on a webpage. 我目前在网页上使用了两个相同的联系表单。 One is on every page- in the banner, and another version of it is in the main section of the contact page itself. 一个在横幅中的每个页面上,而另一个版本在联系页面本身的主要部分中。 This is what I use to validate it: 这是我用它来验证它:

$(".contactform").each(function() {
    $(this).validate();
});

However, when I click submit on either of the forms, the opposite one of it (the unused one) comes back showing errors. 但是,当我在任一表单上单击提交时,其中相反的一个(未使用的表单)返回显示错误。 I don't want the person to have to fill in both (as they are the exact same form) and am a bit confused on where to go from here. 我不希望这个人必须填写两个(因为它们是完全相同的形式)并且对于从这里去哪里感到有点困惑。

What I ended up doing according to xnnyygn's answer was adding in separate .validate rules by id, when done by class or form this would not work and exhibit first selection error result. 根据xnnyygn的回答我最终做的是在id中添加单独的.validate规则,当由类或表单完成时,这将无法工作并显示第一个选择错误结果。

$("#contactform1").validate({
  rules: {
    field: {
      required: true
    }
  }
});

$("#contactform2").validate({
  rules: {
    field: {
      required: true

    }
  }
});


$(document).ready(function(){
  $("#contactform1").validate();
  $("#contactform2").validate();
});

I ended up using two ids instead of a class or form selector here. 我最终在这里使用了两个id而不是类或表单选择器。 Doing otherwise will not work. 否则将无法正常工作。 Lesson learned, with jquery.validator you must use ids. 经验教训,使用jquery.validator必须使用id。

This is my test HTML , from http://docs.jquery.com/Plugins/Validation#source , adding a duplicated form with same class. 这是我的测试HTML ,来自http://docs.jquery.com/Plugins/Validation#source ,添加了一个具有相同类的重复表单。

I've tried to call validate directly, but the first form was validated when I press the second submit button. 我试图直接调用validate,但是当我按下第二个提交按钮时,第一个表单已经过验证。 However, calling validate separately works well. 但是,单独调用validate也很有效。

The reason why validator 'jumps' to another form may be that jquery validator only take the first element(form) and apply the rules. 验证器“跳转”到另一种形式的原因可能是jquery验证器只接受第一个元素(表单)并应用规则。 See the source for more detail. 有关详细信息,请参阅源代码。

Not sure if it solves this problem, but you shouldn't need to use '.each()' explicitly. 不确定它是否解决了这个问题,但你不应该明确地使用'.each()'。 Just write: 写吧:

$(".contactform").validate();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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