Currently i try to validate a property by another property of the same class. I got an error which told me the following:
An object reference is required for a non static field, method or property
This kind of error makes absolute sense to me for the following code snippet. But in anyway i try to validate property A (in my example OrderNumber) in reason of the value of property B (in my example Level).
Is there a possibility to do that by using Validation Annotation?
This is currently my code:
public class A
{
/// <summary>
/// Level
/// </summary>
public string Level { get; set; }
public B B {get;set;}
}
public class B
{
/// <summary>
/// Order Number
/// </summary>
[Level(A.Level)]
public int? OrderNumber { get; set; }
}
public class LevelAttribute : ValidationAttribute
{
private string Dlevel { get; set; }
public LevelAttribute(string dlevel)
{
this.Dlevel = dlevel;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value!=null && (Dlevel.Equals("D1")||Dlevel.Equals("D2")))
{
return new ValidationResult("Invalid Error Message");
}
return ValidationResult.Success;
}
}
Thanks for help.
Directly referencing an instance member (method, property, field) is not possible in a custom attribute constructor. But there is an indirect way by defining the property name and resolve the corresponding property value via reflection: