0
votes

I'm trying to do custom validation attributes messages in .NET Core. The purpose is to automatize work so I don't use ErrorMessage parameter. I've got Required done as shown below:

public class RequiredShortAttribute : RequiredAttribute, IClientModelValidator
{
    public RequiredShortAttribute() : base()
    {
        ErrorMessageResourceType = typeof(ErrorResource);
        ErrorMessageResourceName = "RequiredShort";
    }

    public void AddValidation(ClientModelValidationContext context)
    {
        MergeAttribute(context.Attributes, "data-val-required", FormatErrorMessage(""));
    }

    bool MergeAttribute(IDictionary<string, string> attributes, string key, string value)
    {
        if (attributes.ContainsKey(key))
        {
            return false;
        }
        attributes.Add(key, value);
        return true;
    }
} 

But when I try to make other custom attribute in that way (like StringLength below), the validation doesn't work. Should I add something else?

public class StringLengthShortAttribute : StringLengthAttribute, IClientModelValidator
{
    public StringLengthShortAttribute(int max) : base(max)
    {
        ErrorMessageResourceType = typeof(ErrorResource);
        ErrorMessageResourceName = "StringLengthShort";
    }

    public void AddValidation(ClientModelValidationContext context)
    {
        MergeAttribute(context.Attributes, "data-val-length", FormatErrorMessage(""));
    }

    bool MergeAttribute(IDictionary<string, string> attributes, string key, string value)
    {
        if (attributes.ContainsKey(key))
        {
            return false;
        }
        attributes.Add(key, value);
        return true;
    }
}
1

1 Answers

0
votes

Why don't write the validator as:

    public class ShortStringLengthShortAttribute : StringLengthAttribute
    {
        public ShortStringLengthShortAttribute(int maximumLength) : base(maximumLength)
        {
        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            ValidationResult validationResult = new StringLengthAttribute(MaximumLength).GetValidationResult(value, validationContext);
            if (validationResult == ValidationResult.Success)
            {
                return ValidationResult.Success;
            }

            return new ValidationResult("Put here the error message you want"); 
        }
    }