'how do you set same error message for all required attribute validation?
I am new to .net core. The following code changes all required validation message to "This field is required" for asp.net framework.
public class CustomRequiredAttribute:RequiredAttribute, IClientValidatable
{
public override bool IsValid(object value)
{
return base.IsValid(value);
}
public override string FormatErrorMessage(string name)
{
return base.FormatErrorMessage(name); // expandable to format given message later
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
return new[] { new ModelClientValidationRule { ErrorMessage = "This field is required", ValidationType = "required" } };
}
}
How do you do same for .net core?
public class CustomRequiredAttribute:RequiredAttribute
{
//set required field message to : This field is requried.
}
Solution 1:[1]
For your requirement, you could implement RequiredAttribute, IClientModelValidator
like
public class DefaultRequiredAttribute: RequiredAttribute, IClientModelValidator
{
public DefaultRequiredAttribute()
{
ErrorMessage = "This field is required";
}
public void AddValidation(ClientModelValidationContext context)
{
MergeAttribute(context.Attributes, "data-val", "true");
MergeAttribute(context.Attributes, "data-val-required", ErrorMessage);
}
private bool MergeAttribute(IDictionary<string, string> attributes, string key, string value)
{
if (attributes.ContainsKey(key))
{
return false;
}
attributes.Add(key, value);
return true;
}
}
And use like
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
[DefaultRequired]
public string UserImage { get; set; }
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Edward |