简体   繁体   中英

jQuery validation engine required blocks my custom required validator

I have a form with 2 text inputs and 2 radio buttons. One radio button is when customer wants all future communication to happen via paper mail the other button is when customer wants to communicate via email.

When user chooses email then user needs to fill one of the input textboxes with his email address. When user chooses postal then he has to fill the other box with postal address.

I have a custom jquery validation engine function for this:

function checkBillRoutePostalAddressConflict(field, rules, i, options){
  var fieldValue = field.val();
  var accountIdR = field.attr('id').match(/\d+$/);
  var radioButton = jQuery('#postalBillsDestination_' + accountIdR);
  if(!fieldValue && radioButton.attr("checked")){
    alert('options.allrules.checkBillRoutePostalAddressConflict.alertText') // for debugging
    return options.allrules.checkBillRoutePostalAddressConflict.alertText;
  }
}

Validator is added with class to my input text field class="validate[funcCall[checkBillRoutePostalAddressConflict]]"

The problem is it doesnt work. The debugging alert message shows up which means the conditions are correct. If i replace it with one of my other custom validators then everything works well.

Someone told me that if you write a custom validation function to a field that is empty and shouldnt be then the message is not shown because jQuery wants you to use validate[required].

If this is true, does anybody know some kind of not-too-hacky workaround for this?

One option is to use showPrompt directly, but mabye there is something cleaner and better?
Thank you!

Rule for element can be not just true or false, but also a function. That function could check if email checkbox is checked and return true (false otherwise):

$('#form').validate({
    'rules': {
        'email_text_field': {
            'required': function() { return $('#email-radio').is(':checked'); }
        }
    }           
});

Here default required validator is used.

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