JQuery 表单验证 - 根据其他表单字段验证表单

发布于 2024-09-10 22:59:39 字数 426 浏览 2 评论 0原文

我正在使用 Jquery 表单验证,其基本表单如下所示

$('#shopping_form').validate({          
  submitHandler: function(){
  $.post("/url", { message: messageval}, function(data) {
  ......
  ......
  },
}
,rules: {
    message: { required:true },
    price: { number: true  }                
}
});

现在我向此表单添加两个单选按钮,将它们称为 radio1 和 radio2。 如果选择 radio1,则字段消息是必需的,而对于 radio2,则不是必需字段。

我怎样才能添加这样的规则。 感谢您提前的帮助

I"m using Jquery form validation which in the basic form looks like this

$('#shopping_form').validate({          
  submitHandler: function(){
  $.post("/url", { message: messageval}, function(data) {
  ......
  ......
  },
}
,rules: {
    message: { required:true },
    price: { number: true  }                
}
});

Now I am adding two radio buttons to this form call them radio1 and radio2.
If radio1 is selected then the field message is required and for radio2 its not a required field.

How can I add this kind of rule.
Thanks for your help in advance

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

小女人ら 2024-09-17 22:59:39

您可以通过编写一个自定义方法来执行此操作,该方法检查单选按钮值,并根据该值检查消息字段。这是您可以在 jQuery 中添加的代码

$.Validation.addRule("message",{
 check: function(value) {
    // Check the value of radio button here, You can do it as 
      if($("form input:radio:checked").val() == 'radio2') return true;
     // radio2 is checked then return valid, ie. this field is not required field.
    if(value.length > 0) {
        return true;
    }
    return false;
},
msg : "Field is required."
});

You can do this by writing a custom method which checks radio button value and depending on that value , it checks for message field. Here is the code you can add in jQuery

$.Validation.addRule("message",{
 check: function(value) {
    // Check the value of radio button here, You can do it as 
      if($("form input:radio:checked").val() == 'radio2') return true;
     // radio2 is checked then return valid, ie. this field is not required field.
    if(value.length > 0) {
        return true;
    }
    return false;
},
msg : "Field is required."
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文