我有一个类(应用程序),它具有另一个自定义类(就业)类型的多个属性。我想根据 Application 类的属性是否标有 [Required] 有条件地验证就业类。
根据我的发现,我认为我应该使用 IValidatableObject 接口来就业。问题是我不确定如何使用反射(或其他方法)来检查该类的实例是否用 [Required] 属性注释以确定是否验证它。
也许这甚至是不可能的。我最初为就业类设置了两个类:Employment 和EmploymentRequired。只有后者在其属性上具有验证属性。它有效,但如果可能的话,我只想使用一个类。
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;
}
}