I'm using ef6 with mvc5. My project need multiple language. So I need create a DataAnnotations Attribute for validation these field.
For example: I have a Id property:
public int Id { get; set; }
For validation I need add annotations like
[Display("User Id")]
Required(ErrorMessage = "Please input the Id")
public int Id { get; set; }
But I need use multiple language , So I create a new DataAnnotations Attribute(https://stackoverflow.com/a/2432520/1900498):
public class LocalizedDisplayAttribute : DisplayNameAttribute
{
public LocalizedDisplayAttribute(string resourceId)
: base(GetMessageFromResource(resourceId))
{ }
private static string GetMessageFromResource(string resourceId)
{
// TODO: Return the string from the resource file
}
}
It works fine , but it will cache the result, then when session changed(I'm use session save the user website page language mode. like 1 mean English, 0 mean other language), it still not change, this is a problem for me.
second problem is: I don't know how to rewrite RequiredAttribute for let user know , some field can't empty.
but I also find there is another problem , looks like I need to rewrite the message about numeric field......(xx field must be numeric)
So Is there any way can rewrite the validation rule, let me decide the error message for Required, Range, Numeric...... and it will cache it but when session changed, it will read again?
For example:
// if session changed rewrite rule message for current language
if (session["language"].ToString() != LastLanguage)
{
if (session["language"].ToString() == "1")
//English
{
RequiredMessage = "the field {0} must be required";
NumericMessage = "the field {0} must be a number";
LastLanguage = 1;
} else{
// other language
RequiredMessage = "xx xx {0} xxxxxxxxx";
NumericMessage = "xx xx {0} xxxxxxxxxx";
LastLanguage = 0;
}
}
Of course, not only the validation message, I need globalization the field display name too.