Custom Validation Attributes

In my last post I showed you how to use Validation attributes on your model for validation. Today I will show how you can create your own attributes that can provide custom validation for you.

To accomplish this we need to inherit from ValidationAttribute. We’ll create an attribute today that will only allow a "Yes" or "No" value to be entered. A pretty bad example however it will still suffice.

public class TwoValueAttribute : ValidationAttribute
{
    private string str1 { get; set; }
    private string str2 { get; set; }

    public TwoValueAttribute(string str1, string str2)
    {
        this.str1 = str1;
        this.str2 = str2;
    }

    public override bool IsValid(object value)
    {
        if (value.ToString() == str1 || value.ToString() == str2)
            return true;
        else
            return false;
    }

    public override string FormatErrorMessage(string name)
    {
        return string.Format(CultureInfo.CurrentCulture, 
                             base.ErrorMessageString, 
                             name, this.str1, this.str2);
    }
}

All the validation logic takes place in the IsValid function. You can override the FormatErrorMessage function so that you can supply a custom error message for each instance that you want to validate if you so wish.

I’ll show you what I mean.

public class MyOrder : CustomValidation
{
    [TwoValue("Yes","No", 
        ErrorMessage="Only the values '{1}' and '{1}' are possible"
                + " for the {0} field")]
    public string Value1 { get; set; }

    [TwoValue("Yes", "No")]
    public string Value2 { get; set; }
}


Value2 in the above case will give you the default error message if the value is not "Yes" or "No". However if Value1 is not "Yes" or "No" then the error message supplied will be used and the tokens replaced by the value entered, and the two values used for validation.

And that’s it. Pretty simple really.

Cheers,

Adam

Advertisements
This entry was posted in .NET and tagged . Bookmark the permalink.

One Response to Custom Validation Attributes

  1. param says:

    HI Adam,
    your post here is very good and very useful.
    could you please help me for below:
    i have a method in a class that takes two string parameters

    [isValid(lenght=4)]//attribute
    public void concatStrings(string str1,string str2){—}

    Now, I WANT TO GET THE VALUES OF THE METHOD AND VALIDATE FOR THEIR LENGTHS in the isValid attribute code..

    is it possible?

    thanks
    PARAM

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s