简体   繁体   English

jQuery验证:根据不同的表单字段是否具有值,使用自定义消息添加必需的规则

[英]jquery validate: adding a required rule with custom message based on wether a different form field has a value

I know this seems like a repeat question, but i've read all the others and they arn't quite the same :( 我知道这似乎是一个重复的问题,但是我已经阅读了所有其他文章,但他们的理解不尽相同:(

I've got some drop downs, and if they have something other then an option with a value of "0" selected then I want the coresponding Expiry Date field to be required. 我有一些下拉菜单,如果它们还有其他选项,则选择一个值为“ 0”的选项,那么我需要核心响应的“到期日期”字段。

I tried putting the rule in the class of the objects, and using the rules('add') function. 我尝试将规则放在对象的类中,并使用rules('add')函数。 Here's where i am at right now: 这是我现在所在的位置:

$('[id^=ExpiryDate]').each(function() {

    $(this).rules('add',
    { required: function() {
        if ($('#q' + id).val() == '0') {
            return false;
        }
        else {
            return true;
        }
    } 
    }
);

my expiry date fields are id'ed like "ExpiryDate1", "ExpiryDate2" and the corresponding drop downs are ided like "q1" and "q2". 我的到期日期字段的ID如“ ExpiryDate1”,“ ExpiryDate2”,而相应的下拉列表的ID如“ q1”和“ q2”。

this makes my scripts fail. 这使我的脚本失败。 it doesn't give any errors in the error console or firebug. 它不会在错误控制台或Firebug中提供任何错误。 but it doesn't execute any javascript that occurs after it either. 但它也不会执行在它之后出现的任何JavaScript。

I have a feeling it's something really obvious and stupid that i am missing. 我有一种感觉,我确实很失落,很愚蠢。 but i've been staring at this code for a couple hours now and can't find it! 但我已经盯着这个代码几个小时了,找不到它!

Thanks in advance! 提前致谢!

Try this: 尝试这个:

$('[id^=ExpiryDate]').each(function() {
  var id = $(this).attr('id').replace('ExpiryDate','');
  $(this).rules('add', { 
    required: function() {
      return $('#q' + id).val() !== '0';
    } 
  }
);

Currently, your id is undefined, so it's just not finding any elements. 目前,您的id是未定义的,因此它没有找到任何元素。 The rest is just a shorter version. 其余只是较短的版本。

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

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