18

在 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 field is required”

好的。所以,我去改变我的财产...

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

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

到目前为止一切都很好。

所以现在我希望错误消息显示“First Name Blah Blah”。如何覆盖默认消息以显示 DisplayName +“Blah Blah”,而不用类似的东西注释所有属性

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

干杯,

ETF费尔法克斯

4

8 回答 8

16
public class GenericRequired: RequiredAttribute
{
    public GenericRequired()
    {
        this.ErrorMessage = "{0} Blah blah"; 
    }
}
于 2009-12-18T22:49:51.300 回答
13

似乎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"
        };
    }
}
于 2012-03-28T19:10:33.083 回答
13

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

全球.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")].

于 2014-04-20T07:39:31.980 回答
3

只是改变

[Required] 

[Required(ErrorMessage = "Your Message, Bla bla bla aaa!")]
于 2012-02-03T21:05:08.263 回答
1

编辑:我发布了这个,因为我正在寻找这个具有 [Required] 属性的解决方案并且有问题找到它。创建新的 Q/A 看起来不太好,因为这个问题已经存在。

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

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

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

我在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; }
}
于 2014-02-12T09:04:38.220 回答
0

您可以编写自己的属性:

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 的副本,错误消息已更改。

于 2009-11-27T20:25:07.453 回答
0
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]
于 2016-05-07T13:35:05.283 回答
-1

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

 // 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"
                    };
                }
            }
于 2012-04-11T10:16:05.327 回答