我的视图模型中有以下属性
public IList<KeyWordViewModel> KeyWords { get; set; }
在我的 .cshtml 文件中,我正在呈现这样的复选框:
<div>
@for (int i = 0; i < Model.KeyWords.Count; i++)
{
<div>
@*@Html.HiddenFor(x => x.KeyWords[i].KeyWord)*@
@Html.CheckBoxFor(x => x.KeyWords[i].Checked)
@Html.LabelFor(x => x.KeyWords[i].Checked, Model.KeyWords[i].KeyWord)
</div>
}
</div>
我需要一些方法来使用 jquery jquery.validate.unobtrusive 在客户端验证这组复选框。
有人可以建议。我创建了以下自定义属性,但从未发生客户端验证。
public class CheckListRequiredAttribute : ValidationAttribute, IClientValidatable
{
int _min;
int _max;
string _propertyName;
public CheckListRequiredAttribute(int min = 1, int max = int.MaxValue, string propertyName = "Checked")
{
this._min = min;
this._max = max;
this._propertyName = propertyName;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
IList list;
if (value == null)
{
return null;
}
if (value.GetType().Name == typeof(List<>).Name || value.GetType().Name == typeof(IList<>).Name)
{
list = (IList)value;
}
else
{
list = new object[] { value };
}
if (list.Count < 0)
return null;
var checkedItems = (from object item in list let propertyInfo = item.GetType().GetProperties() from info in propertyInfo where String.Equals(info.Name, _propertyName) && (bool)info.GetValue(item, null) == true select item).ToList();
if (checkedItems.Count >= _min && checkedItems.Count <= _max)
{
return null;
}
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
yield return new ModelClientValidationRule
{
ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
ValidationType = "checklistrequired"
};
}
}
我有以下验证器注册码
$(function () {
jQuery.validator.unobtrusive.adapters.add('checklistrequired', {}, function (options) {
options.rules['checklistrequired'] = {};
if (options.message) {
options.messages['checklistrequired'] = options.message;
}
});
jQuery.validator.addMethod('checklistrequired', function (value, element, params) {
alert("Testing cb validation");
return false;
}, 'Please check at least one box.');
} (jQuery));