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?
Your GenericRequired implementation works only for server-side validation. When creating a subclass of ValidationAttribute, you will only get server-side validation out of the box. In order to make this work with client-side validation, you would need to both implement IClientModelValidator and add a jQuery validator (instructions further down the linked page).
As I suggested in the comments, you can instead just subclass RequiredAttribute to get what you want, e.g.:
public class GenericRequired : RequiredAttribute
{
public GenericRequired()
{
ErrorMessage = "{0} is required";
}
}
All this does is change the ErrorMessage, leaving both the server-side and client-side validation in tact, which is far simpler for your use case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With