为了在自定义属性中启用客户端验证,您可以在属性中实现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));
}
当然,您需要确保您在上述类中引用了您的属性。