MVC:覆盖默认的 ValidationMessage

发布于 2024-08-13 06:21:04 字数 805 浏览 8 评论 0原文

在 MVC 的世界中,我有这个视图模型...

public class MyViewModel{

[Required]
public string FirstName{ get; set; }    }

...在我看来是这样的事情...

<%= Html.ValidationSummary("Please correct the errors and try again.") %>
<%= Html.TextBox("FirstName") %>
<%= Html.ValidationMessage("FirstName", "*") %>

我的问题:如果我提交此表单而不提供姓名,我会收到以下消息“FirstName 字段是需要”

确定。所以,我去将我的属性更改为...

[DisplayName("First Name")]
[Required]
public string FirstName{ get; set; }    

...现在得到“名字字段是必需的”

到目前为止一切都很好。

所以现在我希望错误消息显示“First Name Blah Blah”。如何覆盖默认消息以显示 DisplayName +“Blah Blah”,而不用诸如

[Required(ErrorMessage = "First Name Blah Blah")]

Cheers、

ETFairfax 之类的内容注释所有属性

In the world of MVC I have this view model...

public class MyViewModel{

[Required]
public string FirstName{ get; set; }    }

...and this sort of thing in my view...

<%= Html.ValidationSummary("Please correct the errors and try again.") %>
<%= Html.TextBox("FirstName") %>
<%= Html.ValidationMessage("FirstName", "*") %>

My question: If I submit this form without supplying a name, I get the following message "The FirstName field is required"

OK. So, I go and change my property to...

[DisplayName("First Name")]
[Required]
public string FirstName{ get; set; }    

..and now get "The First Name field is required"

All good so far.

So now I want the error message to display "First Name Blah Blah". How can I override the default message to display DisplayName + " Blah Blah", wihtout annotating all the properties with something like

[Required(ErrorMessage = "First Name Blah Blah")]

Cheers,

ETFairfax

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

べ映画 2024-08-20 06:21:04
public class GenericRequired: RequiredAttribute
{
    public GenericRequired()
    {
        this.ErrorMessage = "{0} Blah blah"; 
    }
}
public class GenericRequired: RequiredAttribute
{
    public GenericRequired()
    {
        this.ErrorMessage = "{0} Blah blah"; 
    }
}
好多鱼好多余 2024-08-20 06:21:04

似乎RequiredAttribute 没有实现IClientValidatable,因此如果您重写RequiredAttribute,它会破坏客户端验证。

这就是我所做的并且有效。希望这对某人有帮助。

public class CustomRequiredAttribute : RequiredAttribute, IClientValidatable
{
    public CustomRequiredAttribute()
    {
        this.ErrorMessage = "whatever your error message is";
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        yield return new ModelClientValidationRule
        {
            ErrorMessage = this.ErrorMessage,
            ValidationType = "required"
        };
    }
}

It seems that RequiredAttribute doesn't implement IClientValidatable, so if you override the RequiredAttribute it breaks client side validation.

So this is what I did and it works. Hope this helps someone.

public class CustomRequiredAttribute : RequiredAttribute, IClientValidatable
{
    public CustomRequiredAttribute()
    {
        this.ErrorMessage = "whatever your error message is";
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        yield return new ModelClientValidationRule
        {
            ErrorMessage = this.ErrorMessage,
            ValidationType = "required"
        };
    }
}
冷夜 2024-08-20 06:21:04

这是一种无需子类化 RequiredAttribute 即可实现的方法。只需制作一些属性适配器类即可。在这里,我使用 ErrorMessageResourceType/ErrorMessageResourceName (带有资源),但您可以轻松设置 ErrorMessage,甚至可以在之前检查是否存在覆盖设置这些。

Global.asax.cs:

public class MvcApplication : HttpApplication {
    protected void Application_Start() {
        // other stuff here ...
        DataAnnotationsModelValidatorProvider.RegisterAdapter(
            typeof(RequiredAttribute), typeof(CustomRequiredAttributeAdapter));
        DataAnnotationsModelValidatorProvider.RegisterAdapter(
            typeof(StringLengthAttribute), typeof(CustomStringLengthAttributeAdapter));
    }
}

private class CustomRequiredAttributeAdapter : RequiredAttributeAdapter {
    public CustomRequiredAttributeAdapter(ModelMetadata metadata, ControllerContext context, RequiredAttribute attribute)
        : base(metadata, context, attribute)
    {
        attribute.ErrorMessageResourceType = typeof(Resources);
        attribute.ErrorMessageResourceName = "ValRequired";
    }
}

private class CustomStringLengthAttributeAdapter : StringLengthAttributeAdapter {
    public CustomStringLengthAttributeAdapter(ModelMetadata metadata, ControllerContext context, StringLengthAttribute attribute)
        : base(metadata, context, attribute)
    {
        attribute.ErrorMessageResourceType = typeof(Resources);
        attribute.ErrorMessageResourceName = "ValStringLength";
    }
}

此示例将让您创建一个名为 Resources.resx 的资源文件,其中 ValRequired 作为新的必需默认消息,使用 ValStringLength 作为字符串长度超出默认消息。请注意,对于两者,{0} 都会接收字段名称,您可以使用 [Display(Name = "Field Name")] 设置该名称。

Here is a way to do it without subclassing RequiredAttribute. Just make some attribute adapter classes. Here I'm using ErrorMessageResourceType/ErrorMessageResourceName (with a resource) but you could easily set ErrorMessage, or even check for the existence of overrides before setting these.

Global.asax.cs:

public class MvcApplication : HttpApplication {
    protected void Application_Start() {
        // other stuff here ...
        DataAnnotationsModelValidatorProvider.RegisterAdapter(
            typeof(RequiredAttribute), typeof(CustomRequiredAttributeAdapter));
        DataAnnotationsModelValidatorProvider.RegisterAdapter(
            typeof(StringLengthAttribute), typeof(CustomStringLengthAttributeAdapter));
    }
}

private class CustomRequiredAttributeAdapter : RequiredAttributeAdapter {
    public CustomRequiredAttributeAdapter(ModelMetadata metadata, ControllerContext context, RequiredAttribute attribute)
        : base(metadata, context, attribute)
    {
        attribute.ErrorMessageResourceType = typeof(Resources);
        attribute.ErrorMessageResourceName = "ValRequired";
    }
}

private class CustomStringLengthAttributeAdapter : StringLengthAttributeAdapter {
    public CustomStringLengthAttributeAdapter(ModelMetadata metadata, ControllerContext context, StringLengthAttribute attribute)
        : base(metadata, context, attribute)
    {
        attribute.ErrorMessageResourceType = typeof(Resources);
        attribute.ErrorMessageResourceName = "ValStringLength";
    }
}

This example would have you create a resource file named Resources.resx with ValRequired as the new required default message and ValStringLength as the string length exceeded default message. Note that for both, {0} receives the name of the field, which you can set with [Display(Name = "Field Name")].

日暮斜阳 2024-08-20 06:21:04

只需更改

[Required] 

[Required(ErrorMessage = "Your Message, Bla bla bla aaa!")]

Just change

[Required] 

to

[Required(ErrorMessage = "Your Message, Bla bla bla aaa!")]
蓝咒 2024-08-20 06:21:04

编辑:我发布此内容是因为我正在寻找具有 [Required] 属性的解决方案,但找不到它。创建新的问答看起来不太好,因为这个问题已经存在。

我试图解决同样的问题,并在 MVC 4 中找到了非常简单的解决方案。

首先,您可能必须在某个地方存储错误消息。我使用了自定义资源,在 http://afana.me/post/aspnet-mvc 中有详细描述-国际化.aspx

重要的是,我可以通过简单地调用 ResourcesProject.Resources.SomeCustomErrorResourcesProject.Resources.MainPageTitle 等来获取任何资源(甚至是错误消息)。每次我尝试访问资源时类,它从当前线程获取文化信息并返回正确的语言。

我在 ResourcesProject.Resources.RequiredAttribute 中收到字段验证错误消息。要设置此消息显示在视图中,只需使用这两个参数更新 [Required] 属性即可。

ErrorMessageResourceType - 将被调用的类型(在我们的示例中ResourcesProject.Resources)

ErrorMessageResourceName - 属性,将在上面的类型上调用(在我们的例子中为RequiredAttribute)

这是一个非常简化的登录模型,仅显示用户名验证消息。当该字段为空时,它将从 ResourcesProject.Resources.RequiredAttribute 中获取字符串并将其显示为错误。

    public class LoginModel
    {        
        [Required(ErrorMessageResourceType = typeof(Resources.Resources), ErrorMessageResourceName="RequiredAttribute")]
        [Display(Name = "User name")]
        public string UserName { get; set; }
}

Edit: I posted this because I was looking for this solution with [Required] attribute and had problem to find it. Creating new Q/A don't look that good, since this question already exists.

I was trying to solve the same thing and I found very simple solution in MVC 4.

First, you would probably have to store error messages in some place. I used custom resources, well described at http://afana.me/post/aspnet-mvc-internationalization.aspx.

Important is, that I can get any resource (even error message) by simply calling ResourcesProject.Resources.SomeCustomError or ResourcesProject.Resources.MainPageTitle etc. Everytime I try to access Resources class, it takes culture info from current thread and returns right language.

I have error message for field validation in ResourcesProject.Resources.RequiredAttribute. To set this message to appear in View, simply update [Required] attribute with these two parameters.

ErrorMessageResourceType - Type which will be called (in our example ResourcesProject.Resources)

ErrorMessageResourceName - Property, which will be called on the type above (In our case RequiredAttribute)

Here is a very simplified login model, which shows only username validation message. When the field is empty, it will take the string from ResourcesProject.Resources.RequiredAttribute and display this as an error.

    public class LoginModel
    {        
        [Required(ErrorMessageResourceType = typeof(Resources.Resources), ErrorMessageResourceName="RequiredAttribute")]
        [Display(Name = "User name")]
        public string UserName { get; set; }
}
远昼 2024-08-20 06:21:04

您可以编写自己的属性:

public class MyRequiredAttribute : ValidationAttribute
{
    MyRequiredAttribute() : base(() => "{0} blah blah blah blaaaaaah")
    {

    }

    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;
    }
}

这是来自 Reflector 的RequiredAttribute 的副本,并更改​​了错误消息。

You can write your own attribute:

public class MyRequiredAttribute : ValidationAttribute
{
    MyRequiredAttribute() : base(() => "{0} blah blah blah blaaaaaah")
    {

    }

    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;
    }
}

This is copy of RequiredAttribute from Reflector with changed error message.

流云如水 2024-08-20 06:21:04
using Resources;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Web;
using System.Web.Mvc;

public class CustomRequiredAttribute : RequiredAttribute,  IClientValidatable
{
    public CustomRequiredAttribute()
    {
        ErrorMessageResourceType = typeof(ValidationResource);
        ErrorMessageResourceName = "RequiredErrorMessage";
    }


    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {


        yield return new ModelClientValidationRule
        {
            ErrorMessage = GetRequiredMessage(metadata.DisplayName),
            ValidationType = "required"
        };
    }


    private string GetRequiredMessage(string displayName) {

        return displayName + " " + Resources.ValidationResource.RequiredErrorMessageClient;        

    }


}

App_GlobalResources/ValidationResource.resx

在此处输入图像描述

现在使用数据注释

[CustomRequired]
using Resources;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Web;
using System.Web.Mvc;

public class CustomRequiredAttribute : RequiredAttribute,  IClientValidatable
{
    public CustomRequiredAttribute()
    {
        ErrorMessageResourceType = typeof(ValidationResource);
        ErrorMessageResourceName = "RequiredErrorMessage";
    }


    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {


        yield return new ModelClientValidationRule
        {
            ErrorMessage = GetRequiredMessage(metadata.DisplayName),
            ValidationType = "required"
        };
    }


    private string GetRequiredMessage(string displayName) {

        return displayName + " " + Resources.ValidationResource.RequiredErrorMessageClient;        

    }


}

App_GlobalResources/ValidationResource.resx

enter image description here

Now use data annotation

[CustomRequired]
盛装女皇 2024-08-20 06:21:04

这对我有用。仔细阅读代码里面的注释。 (基于乍得的回答)。

 // Keep the name the same as the original, it helps trigger the original javascript 
 // function for client side validation.

        public class RequiredAttribute : System.ComponentModel.DataAnnotations.RequiredAttribute, IClientValidatable
            {
                public RequiredAttribute()
                {
                    this.ErrorMessage = "Message" // doesnt get called again. only once.
                }

                public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
                {
                    yield return new ModelClientValidationRule
                    {
                        ErrorMessage = "Message", // this gets called on every request, so it's contents can be dynamic.
                        ValidationType = "required"
                    };
                }
            }

This worked for me. Carefully read the comments inside the code. (Based on Chad's answer).

 // Keep the name the same as the original, it helps trigger the original javascript 
 // function for client side validation.

        public class RequiredAttribute : System.ComponentModel.DataAnnotations.RequiredAttribute, IClientValidatable
            {
                public RequiredAttribute()
                {
                    this.ErrorMessage = "Message" // doesnt get called again. only once.
                }

                public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
                {
                    yield return new ModelClientValidationRule
                    {
                        ErrorMessage = "Message", // this gets called on every request, so it's contents can be dynamic.
                        ValidationType = "required"
                    };
                }
            }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文