简体   繁体   中英

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.

I tried putting the rule in the class of the objects, and using the rules('add') function. 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".

this makes my scripts fail. it doesn't give any errors in the error console or firebug. but it doesn't execute any javascript that occurs after it either.

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. The rest is just a shorter version.

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