0

I do have a View bound to a model,

When I am using a built-in Validator on a property in the model, [EmailAddress] for instance, if I write something invalid, the html tag gets the class input-validation-error. Which allows me to display it in red via css. That's works perfectly.

But when I am using my custom validators, like :

public class CONT_RU06Attribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value != null)
        {
            int value = int.Parse(value.ToString());

            if (value < 2 || value > 6)                
                return new ValidationResult("Value must be between 2 and 6");
        }

        return ValidationResult.Success;
    }
}

The bound html tag does not get the input-validation-error class... What can I do ?

1 Answer 1

2

You need to implement IClientValidatable also

public class CONT_RU06Attribute : ValidationAttribute, IClientValidatable
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value != null)
        {
            int value = int.Parse(value.ToString());

            if (value < 2 || value > 6)                
                return new ValidationResult("Value must be between 2 and 6");
        }

        return ValidationResult.Success;
    }
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule();
        rule.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName());           
        rule.ValidationType = "range";
        yield return rule;
    }

}

Check this article

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.