$.validator.addMethod('requiredif',
function (value, element, parameters) {
var id = '#' + parameters['dependentproperty'];
var targetvalue = parameters['targetvalue'];
targetvalue =
(targetvalue == null ? '' : targetvalue).toString();
var control = $(id);
var controltype = control.attr('type');
var actualvalue =
controltype === 'checkbox' ?
(control[0].checked?'checked':'') :
control.val();
if(controltype === 'radio') {
var controlname = control.attr('name');
actualvalue = $("input[name='"+controlname+"']:checked").val()+'';
console.log('actualvalue',actualvalue);
}
if (targetvalue === actualvalue)
return $.validator.methods.required.call(
this, value, element, parameters);
return true;
}
);
$.validator.unobtrusive.adapters.add(
'requiredif',
['dependentproperty', 'targetvalue'],
function (options) {
console.log(options);
options.rules['requiredif'] = {
dependentproperty: options.params['dependentproperty'],
targetvalue: options.params['targetvalue']
};
options.messages['requiredif'] = options.message;
});
使用方法
checkbox
<input id="checkbox1" name="dummy" type="checkbox" />
<input type="text" data-val="true" data-val-requiredif="請說明" data-val-requiredif-dependentproperty="checkbox1" data-val-requiredif-targetvalue="checked"/>
radio
<input id="radio1" value="a" name="dummy" type="radio" />
<input type="text" data-val="true" data-val-requiredif="請說明" data-val-requiredif-dependentproperty="radio1" data-val-requiredif-targetvalue="a"/>