Custom error message on model validation ASP.NET Core MVC
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.
Related videos on Youtube
Comments
-
Divyang Desai almost 2 years
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?
-
Kirk Larkin almost 6 yearsWhat's wrong with just using
[Required(ErrorMessage = "{0} is required")]
? -
Divyang Desai almost 6 yearsThanks! @KirkLarkin I don't want to write is required every time, it will take time while changing the text.
-
Kirk Larkin almost 6 yearsYes, I thought you might come back with that. Your code works for me, so it must be something else you're missing. But anyway, I'd recommend you create a subclass of the
RequiredAttribute
and don't reinvent theIsValid
functionality. -
Divyang Desai almost 6 years@KirkLarkin: Did you check with Core? it works? okay, I will give a try with
RequiredAttribute
-
Divyang Desai almost 6 years@KirkLarkin: Do I need to register
GenericRequired
class anywhere? I have checked with another solution, not working :( -
Divyang Desai almost 6 yearsHere to go:RazorPagesDemo customer model
-
-
Divyang Desai almost 6 yearsI'm following this validation sample project for client side validation, however it also work server side :(
-
Kirk Larkin almost 6 yearsYes, of course. It implements both server-side and client-side validation, whereas your
GenericRequired
implements server-side only.