Localizing Error Messages In ASP.NET MVC 2 (Default Validation Attributes)

試著忘記壹切 提交于 2020-01-02 05:55:28

问题


i'm working on a multi language website and i want to localize the validation error messages for most of the ValidationAttribute such as [Requried]

I know it can be done as Phil Haack have shown in this article.

[Required(ErrorMessageResourceType = typeof(Resources), 
ErrorMessageResourceName = "Required")]

but i want to to customize the error message the way i did with my custom Validation Attributes in here :

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property,
                                     AllowMultiple = false,
                                     Inherited = true)]
public sealed class ValidateminRequiredNonalphanumericCharactersAttribute
: ValidationAttribute
{

    private const string _defaultErrorMessage = // Message From Resource Here ( i will be using two variables in this message ) 
    private readonly int _minnonalphanumericCharactersCounter = Membership.Provider.MinRequiredNonAlphanumericCharacters;

    public ValidateminRequiredNonalphanumericCharactersAttribute()
        : base(_defaultErrorMessage)
    {
    }

    public override string FormatErrorMessage(string name)
    {
        return String.Format(CultureInfo.CurrentUICulture, 
            ErrorMessageString, name, _minnonalphanumericCharactersCounter);
    }

    public override bool IsValid(object value)
    {
        string valueAsString = value as string;

        if (String.IsNullOrEmpty(valueAsString))
            return false;

        int nonalphanumericCharactersCounter = 0;
        char[] password = valueAsString.ToCharArray();

        foreach (char c in password)
        {
            if (!char.IsNumber(c) && !char.IsLetter(c))
                nonalphanumericCharactersCounter++;
        }

        return (nonalphanumericCharactersCounter >= _minnonalphanumericCharactersCounter);
    }
}

any idea ?


回答1:


I figured out how it's done. it's really simple and straight.

What i did is that I created my own custom RequiredAttribute. instead of using the built in RequiredAttribute.

The only down side is that you will need to implement the logic of that validator by yourself.

I know some might think it's an over head to re-implement something that is already there. (reinventing the wheel) but this way I will have full control over the Validator logic and error message.

As you can see the logic is implemented in the IsValid() Method below.

Here's the RequiredAttribute class that I've created :

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, 
                                         AllowMultiple = true, 
                                         Inherited = true)]
public sealed class RequiredAttribute : ValidationAttribute
{
    private const string _defaultErrorMessage = // Error Message
    // Notice that i can include the filed name in the error message 
    // which will be provided in the FormatErrorMessage Method 

    public RequiredAttribute()
        : base(_defaultErrorMessage)
    {
    }

    public override string FormatErrorMessage(string name)
    {
        return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString,
            name);
    }

    public override bool IsValid(object value)
    {
        if (value == null || String.IsNullOrWhiteSpace(Convert.ToString(value)))
            return false;
        else
            return true;
    }
}

now when it comes to using the Validator you will need to provide the full reference of your new class as it will collide with the default built in System.ComponentModel.DataAnnotations.RequiredAttribute class in my example above.

in my case this is what the final results looks like :

    [Amaly.Data.Validators.Required]
    public string Username { get; set; }

Hope this was useful.



来源:https://stackoverflow.com/questions/3541107/localizing-error-messages-in-asp-net-mvc-2-default-validation-attributes

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