我有自定义的 ValidationAttribute 和实现的 IClientValidatable。它使用(Html.BeginForm())效果很好,但使用(Ajax.BeginForm())不起作用。
客户端代码:
$(function() {
jQuery.validator.unobtrusive.adapters.addBool('collectionLength');
});
服务器代码:
/// <summary>
/// Require a minimum length, and optionally a maximum length, for any IEnumerable
/// </summary>
sealed public class CollectionMinimumLengthValidationAttribute : ValidationAttribute, IClientValidatable
{
const string errorMessage = "{0} must contain at least {1} item(s).";
const string errorMessageWithMax = "{0} must contain between {1} and {2} item(s).";
int minLength;
int? maxLength;
public CollectionMinimumLengthValidationAttribute(int min)
{
minLength = min;
maxLength = null;
}
public CollectionMinimumLengthValidationAttribute(int min, int max)
{
minLength = min;
maxLength = max;
}
//Override default FormatErrorMessage Method
public override string FormatErrorMessage(string name)
{
if (maxLength != null)
{
return string.Format(errorMessageWithMax, name, minLength, maxLength.Value);
}
else
{
return string.Format(errorMessage, name, minLength);
}
}
public override bool IsValid(object value)
{
IEnumerable<object> list = value as IEnumerable<object>;
if (list != null && list.Count() >= minLength && (maxLength == null || list.Count() <= maxLength))
{
return true;
}
else
{
return false;
}
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule { ValidationType = " CollectionMinimumLengthValidation", ErrorMessage = FormatErrorMessage("Error") };
rule.ValidationParameters.Add("min", minLength);
rule.ValidationParameters.Add("max", maxLength);
yield return rule;
}
}
CollectionMinimumLengthValidation.js 文件:
jQuery.validator.addMethod("CollectionMinimumLengthValidation", function (value, element, param) {
debugger;
return false;
});