我创建了一个新的自定义IClientValidatable
属性:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class MultipleRequiredValuesAttribute : RequiredAttribute, IClientValidatable
{
#region IClientValidatable Members
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var clientValidationRule = new ModelClientValidationRule()
{
ErrorMessage = base.ErrorMessage,
ValidationType = "multiplerequiredvalues"
};
return new[] { clientValidationRule };
}
#endregion
}
并将其应用于我的模型:
[DisplayName("Ages(s)")]
[MultipleRequiredValues(ErrorMessage = "You must provide ages for all children in all rooms")]
public ICollection<int> ChildAges { get; set; }
然后我可以添加 JQuery 端:
(function ($) {
$.validator.addMethod('multiplerequiredvalues', function (value, element) {
if ($(element).is(':visible')) {
var returnVal = true;
var name = $(element).attr('name');
var elements;
if ($(element).is('input')) {
elements= $('input[name='+name+']');
}
else
{
elements= $('select[name='+name+']');
}
elements.each(function() {
if ($(this).is(':visible'))
{
returnVal = $(this).val() != "" && $(this).val() != null;
}
});
return returnVal;
}
else {
return true;
}
});
$.validator.unobtrusive.adapters.addBool("multiplerequiredvalues");
} (jQuery));
请注意,如果元素不可见,这也会返回 true