4

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 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

After you pointed me to this answer I copied your code and included it in my app then later found out there's a nasty bug in it (it took me hours to figure out why the validation with my custom attribute was strange. The error is in IsValid() method. This method should contain this: if (value == null || String.IsNullOrWhiteSpace(value.ToString())) { return false; } return true;
please correct it for other's sake. The point is to remove the as string casting cause its problematic with various value types.
@mare Thanks for fixing my buggy code ,,, I guess I didn't have this issue bcoz I used my Validator with primitive types only.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.