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;
}
}