Custom attribute for changing a property value

I have a class called say

Class1
  public string store { get; set; }

I want to decorate it with something like this:

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

So the value may be 1234, or it may be1234 - Store name

What I need to do is check to see if the value passed is only a number. If this is not the case, I need, in the second example, to capture the first 4 chrs and change the value of the property to this.

So, if the transmitted value was 1234 - Store name, then in the end the [GetStoreNumberFromName]value storeshould be 1234, so it [IsNumeric]will be considered valid.

0
source share
1 answer

Ok .. I hope I 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;
    }
}

.. use:

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

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

.. , .. ( , , , .:/)

, , .

0

All Articles