IClientValidatableが実装されたカスタムValidationAttributeがあります。(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;
});