I'm working with ASP.NET Core MVC project, in which we want to set custom message to required field with filed name instead of generic message given by framework.
For that I I have created a custom class as below:
public class GenericRequired : ValidationAttribute
{
public GenericRequired() : base(() => "{0} is required")
{
}
public override bool IsValid(object value)
{
if (value == null)
{
return false;
}
string str = value as string;
if (str != null)
{
return (str.Trim().Length != 0);
}
return true;
}
}
And using that class in a model.
[GenericRequired]
[DisplayName("Title")]
public string Name { get; set; }
On view page:
<span asp-validation-for="Name" class="text-danger"></span>
But message not displaying or validation doesn't work. Is there any other way to make it work?
[Required(ErrorMessage = "{0} is required")]?RequiredAttributeand don't reinvent theIsValidfunctionality.RequiredAttribute