Search code examples
c#asp.net-mvccustom-attributesmodel-validation

pass prop as param to another prop custom attribute c#


i want to pass a property as a parameter to another property custom attribute but i can't because its not static Model ex :

public class model1
{
     public DateTime param1 { get; set; }
     [CustomAttribute (param1)]
     public string param2 { get; set; }
}

public class CustomAttribute : ValidationAttribute
{
    private readonly DateTime _Date;
    public CustomAttribute(DateTime date)
    {
        _Date= date;
    }
}

because i want to make a custom validation between this two attributes .


Solution

  • Attributes are not stored as executable code, so there are significant limitations on the kind of data you can include in them.

    Basically, you must stick with base types: strings, numbers, dates. Everything that can be a constant.

    Fortunately, you can use a bit of reflection and the nameof operator:

    public class model1
    {
         public DateTime param1 { get; set; }
         [CustomAttribute (nameof(param1))]
         public string param2 { get; set; }
    }
    
    public class CustomAttribute : ValidationAttribute
    {
        private readonly string _propertyName;
        public CustomAttribute(string propertyName)
        {
            _propertyName = propertyName;
        }
    }
    

    Keep in mind that the validation logic should reside outside the attribute's code.

    The needed ingredients for the validation will be Type.GetProperties, PropertyInfo.GetValue, and MemberInfo.GetCustomAttribute.

    If you need a complete example and care to better explain the use case, let me know.