开发者

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

i'm working on a multi language website and i want to localize the validation error开发者_Python百科 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 ?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜