カスタム属性でクライアント検証を有効にするためにIClientValidatable
、属性にインターフェースを実装できます。
public class requiredAttribute : ValidationAttribute, IClientValidatable
{
...
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
return new[] { new ModelClientValidationRule { ErrorMessage = "<Your error message>", ValidationType = "required" } };
}
}
別の方法として、属性の検証アダプターを実装できます。
public class requiredAttributeAdapter : DataAnnotationsModelValidator<requiredAttribute>
{
public requiredAttributeAdapter(ModelMetadata metadata, ControllerContext context, RequiredAttribute attribute)
: base(metadata, context, attribute)
{ }
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
return new[] { new ModelClientValidationRule { ErrorMessage = "<Your error message>", ValidationType = "required" } };
}
}
そして、Global.asaxのデータ注釈検証エンジンに登録します。
protected void Application_Start()
{
...
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(requiredAttribute), typeof(requiredAttributeAdapter));
}
もちろん、上記のクラスで属性を参照していることを確認する必要があります。