0

I have a class called say

Class1
  public string store { get; set; }

What I want is to decorate it with something like this;

Class1
  [GetStoreNumberFromName]
  [IsNumeric]
  public string store {get; set; }

So the value might be 1234, or it might be 1234 - Store name

What I need to do is check to see if the value passed has only numbers in it. If it doesn't then I need, in the second example, to grab the first 4 chrs and change the value of the property to that.

So if the passed in value was 1234 - Store Name then at the end of [GetStoreNumberFromName] the value of store should be 1234 so that [IsNumeric] will pass as valid.

2
  • What is the difference between handling this in a separate class and writing a class that iterates over attributes? Are attributes a bit of overkill for your requirement? Commented Jul 12, 2013 at 3:56
  • @SimonWhitehead, not really overkill because I use them on the class for validation, error messages and whether the field is required. So I would like to intercept the value and modify it so that normal validation can pass the value and not fail it Commented Jul 12, 2013 at 3:59

1 Answer 1

0

Okay.. hopefully I've understood your requirement:

class GetStoreNumberFromNameAttribute : Attribute {
}

class Class1 {
    [GetStoreNumberFromName]
    public string store { get; set; }
}

class Validator<T>
{
    public bool IsValid(T obj)
    {
        var propertiesWithAttribute = typeof(T)
                                      .GetProperties()
                                      .Where(x => Attribute.IsDefined(x, typeof(GetStoreNumberFromNameAttribute)));

        foreach (var property in propertiesWithAttribute)
        {
            if (!Regex.Match(property.GetValue(obj).ToString(), @"^\d+$").Success)
            {
                property.SetValue(obj, Regex.Match(property.GetValue(obj).ToString(), @"\d+").Groups[0].Value);
            }
        }

        return true;
    }
}

..usage:

var obj = new Class1() { store = "1234 - Test" };
Validator<Class1> validator = new Validator<Class1>();
validator.IsValid(obj);

Console.WriteLine(obj.store); // prints "1234"

..obviously needs some changes on your end.. but it should give you an idea (I'm aware that the method naming probably isn't the best.. :/)

If I've missed the point entirely let me know and I'll delete.

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

Comments

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.