模型验证 ASP.NET Core MVC 上的自定义错误消息

Div*_*Div 2 c# validation asp.net-core-mvc asp.net-core

我正在使用 ASP.NET Core MVC 项目,在该项目中,我们希望将自定义消息设置为带有字段名称的必填字段,而不是框架给出的通用消息。
为此,我创建了一个自定义类,如下所示:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

并在模型中使用该类。

[GenericRequired]
[DisplayName("Title")]        
public string Name { get; set; }
Run Code Online (Sandbox Code Playgroud)

在查看页面:

<span asp-validation-for="Name" class="text-danger"></span>
Run Code Online (Sandbox Code Playgroud)

但消息不显示或验证不起作用。有没有其他方法可以使它工作?

Kir*_*kin 5

您的GenericRequired实现仅适用于服务器端验证。创建 的子类时ValidationAttribute,您将只能获得开箱即用的服务器端验证。为了使其与客户端验证一起工作,您需要实现IClientModelValidator并添加一个 jQuery 验证器(链接页面下方的说明)。

正如我在评论中建议的那样,您可以改为子类化RequiredAttribute以获得您想要的内容,例如:

public class GenericRequired : RequiredAttribute
{
    public GenericRequired()
    {
        ErrorMessage = "{0} is required";
    }
}
Run Code Online (Sandbox Code Playgroud)

所有这一切都改变了ErrorMessage,使服务器端和客户端验证都保持原样,这对于您的用例来说要简单得多。

  • 是的当然。它实现了服务器端和客户端验证,而您的“GenericRequired”仅实现了服务器端。 (2认同)