Adrian
Adrian

Reputation: 720

Read validation attribute from Object

I have an object which has properties decorated with Validation attributes. My validation is working correctly, however I need an additional method which performs string manipulation based on those attributes.

Consider the following object:

public class Pupil
{
    /// <summary>
    /// 
    /// </summary>
    public Pupil()
    {

    }

    [NotNullValidator]
    [StringLengthValidator(0, 54, MessageTemplate = "Invalid value '{0}' for {1}, Max length: {5}")]
    public string Name{ get; set; }

    [NotNullValidator]
    [StringLengthValidator(0, 2, MessageTemplate = "Invalid value '{0}' for {1}, Max length: {5}")]
    public string Gender{ get; set; }
}

I want to be able to manipulate the "Name" based on the StringLengthValidator attribute and its arguments. For example:

///Takes a Pupil object in
public static void DoManipulation(object value)
    {
        foreach(var property in value.GetType().GetProperties())
        {
            if(property.Name == "Name")
            {
                var att = property.GetCustomAttributes(typeof(StringLengthValidator), false);
                var length = ((StringLengthValidator)att[0]).UpperBound;

            }               
        }
    }

The value of "length" is coming up as null, rather than 54. How do I get the value out? Hopefully this makes sense, thanks.

A

Upvotes: 2

Views: 3081

Answers (3)

Lucas Tambarin
Lucas Tambarin

Reputation: 405

As I was looking for it today with my co-worker and we did not find a proper solution to our problem, here is the answer, for the next one who is in trouble.

The attribute name is StringLengthValidator, but if you check at the class name it is StringLengthValidatorAttribute, so in order to get the proper attribute, you need to call the function GetCustomAttributes this way :

property.GetCustomAttributes(typeof(StringLengthValidatorAttribute), false)

This will fetch correctly the attribute and then you will be able to get the value of UpperBound

Upvotes: 0

wal
wal

Reputation: 17719

This works for me, are you getting the same StringLengthValidator attribute that you think you are? (is this your custom class or the one from Enterprise Lib?

In my case, I created a custom class StringLengthValidator

enter image description here

Upvotes: 1

Diego
Diego

Reputation: 36136

The idea behind all this is that the value 54 can be changed, right? Otherwise you could just hard code 54.

Take a look on how to contol validation in the web.config with the tag so you can add the 54 to the web.config and read it from your application

Here is an example, look for the first approach, Rule sets in Configuration

Upvotes: 0

Related Questions