Note that there are some explanatory texts on larger screens.

plurals
  1. POCheck if instance of class is annotated with attribute
    text
    copied!<p>I have a class (Application) that has multiple properties of the type of another custom class (Employment). I would like to validate that Employment class conditionally based on whether the property of the Application class is marked with [Required].</p> <p>From what I've found, I think I should be utilizing the IValidatableObject interface for Employment. The problem is that I'm not sure how to use reflection (or something else maybe) to check if this instance of the class is annotated with the [Required] attribute to determine whether to validate it or not. </p> <p>Maybe this isn't even possible. I initially set up two classes for the Employment class: Employment and EmploymentRequired. Only the latter had the validation attributes on its properties. It works, but I'd like to just have one class to use if possible.</p> <pre><code>public class Application { [Required] public Employment Employer1 { get; set; } public Employment Employer2 { get; set; } } public class Employment : IValidatableObject { [Required] public string EmployerName { get; set; } [Required] public string JobTitle { get; set; } public string Phone { get; set; } public IEnumerable&lt;ValidationResult&gt; Validate(ValidationContext validationContext) { var results = new List&lt;ValidationResult&gt;(); var t = this.GetType(); //var pi = t.GetProperty("Id"); //var isRequired = Attribute.IsDefined(pi, typeof(RequiredAttribute)); //how can I get the attributes of this property in Application class? if (isRequired) { Validator.TryValidateProperty(this.EmployerName, new ValidationContext(this, null, null) { MemberName = "EmployerName" }, results); Validator.TryValidateProperty(this.JobTitle, new ValidationContext(this, null, null) { MemberName = "JobTitle" }, results); } return results; } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload