Get the enclosing class, then access its properties inside the custom attribute

I use ASP.NET MVC and implement custom validation using custom data attributes / annotations on my models.

Is it possible to access a property in the parent class of an object inside my custom attribute?

public class MyModel
{
    [MyCustomValidator]
    public string var1 {get; set;}
    public string var2 {get; set;}
}

Note. Using asp.net mvc

public class MyCustomValidatorAttribute : ValidationAttribute
{
    public bool override IsValid(Object value)
    {  
          // somehow get access to var2 in the MyModel
    }
}

So basically, so that the check checks another property for a specific value. I tried passing the value var2as a parameter MyCustomValidator, but this will not work.

+3
source share
3 answers

-, MVC 2 Validation validationContext, MVC 2 DA 3.5. , MVC 2 RC, VS 2010 MVC 2 Preview 1.

http://forums.asp.net/p/1457591/3650720.aspx

3.5A DataAnnotations , MVC 2. [CustomValidation] DA4.0, , ValidationAttribute

+1

, . , //.

, , , 4.0 - , 4.0 IsValid, ValidationContext, ObjectInstance.

+3

Just note that you can do this with MVC3:

public class MyCustomValidatorAttribute : ValidationAttribute
{
    public bool override IsValid(Object value)
    {  
          var model = validationContext.ObjectInstance as MyModel; 
          // would probably use reflection and pass property names instead of casting in real life

          if (model.var2 != null && value == null)
          {
            return new ValidationResult("var1 is required when var2 is set");
          }

          return ValidationResult.Success;
    }
}
0
source

Source: https://habr.com/ru/post/1729659/


All Articles