Friday, 27 September 2013

Check if instance of class is annotated with atribute

Check if instance of class is annotated with atribute

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].
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.
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.
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<ValidationResult> Validate(ValidationContext
validationContext)
{
var results = new List<ValidationResult>();
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;
}
}

No comments:

Post a Comment