Change default “The {0} field is required” (ultimate solution?)

て烟熏妆下的殇ゞ 提交于 2019-12-06 06:14:54

You can create a custom ValidationAttribute that extends RequiredAttribute and sets the values there. Something like:

public class MyRequiredAttribute : RequiredAttribute
{
    public MyRequiredAttribute()
    {
         ErrorMessageResourceType = typeof(Resources.ValidationErrors);
         ErrorMessageResourceName = "Required";
    }
}

Then decorate your Model with your custom attribute.

The default message is compiled into the DataAnnotations assembly in the resource file under System.ComponentModel.DataAnnotations.Resources.DataAnnotationsResources.resources and is RequiredAttribute_ValidationError=The {0} field is required.. So to answer your question, yes, that message is part of DataAnnotations.

Edit: PropertyValueRequired is used for errors on null values with non-nullable types. As mentioned below PropertyValueInvalid is used for type conversion errors.

I've done an approach using a singleton class to provide the translations. You still need to derive all attributes as suggested by @bmancini. The upside with my approach is that you can use multiple string tables (or switch translation source) without having to modify any other logic.

Since my blog entry is rather large, I'll just provide a link: http://blog.gauffin.org/2010/11/simplified-localization-for-dataannotations/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!