To enable client validation in a user attribute, you can implement the IClientValidatable interface in your attribute:
public class requiredAttribute : ValidationAttribute, IClientValidatable { ... public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) { return new[] { new ModelClientValidationRule { ErrorMessage = "<Your error message>", ValidationType = "required" } }; } }
Alternatively, you can implement a validation adapter for your attribute:
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" } }; } }
And register it using the data annotation check mechanism in the Global.asax file:
protected void Application_Start() { ... DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(requiredAttribute), typeof(requiredAttributeAdapter)); }
Of course, you need to make sure that you refer to your attribute in the above classes.
source share