Divyang Desai
Divyang Desai

Reputation: 7866

Custom error message on model validation ASP.NET Core MVC

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?

Upvotes: 4

Views: 14889

Answers (1)

Kirk Larkin
Kirk Larkin

Reputation: 93053

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.

Upvotes: 7

Related Questions