Change default “The {0} field is required” (ultimate solution?)
-
09-10-2019 - |
Question
Good day!
I've the following ViewModel class I use for login form:
using System.ComponentModel.DataAnnotations;
...
public class UserLogin : IDataErrorInfo
{
[Required]
[DisplayName("Login")]
public string Login { get; set; }
[Required]
[DisplayName("Password")]
public string Password { get; set; }
[DisplayName("Remember Me")]
public bool RememberMe { get; set; }
#region IDataErrorInfo Members
// This will be a Model-level error
public string Error
{
get
{
if (!WebUser.CanLogin(Login, Password))
{
return Resources.ValidationErrors.InvalidLoginPassword;
}
else
{
return String.Empty;
}
}
}
// All is handled by DataAnnotation attributes, just a stub for interface
public string this[string columnName]
{
get
{
return string.Empty;
}
}
#endregion
}
And this in Global.asax
:
DefaultModelBinder.ResourceClassKey = "BinderMessages";
ValidationExtensions.ResourceClassKey = "BinderMessages";
The resource file BinderMessages.resx
is placed inside App_GlobalResources it has two keys InvalidPropertyValue
(which works) and PropertyValueRequired
which doesn't and gives me default message.
Question: Is it possible to modify this message, or it's tied to DataAnnotations?
I've found many posts about this, but without solution. For now I just fallback to this:
[Required(ErrorMessageResourceType = typeof(Resources.ValidationErrors), ErrorMessageResourceName = "Required")]
Solution
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.
OTHER TIPS
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/