我有以下表单模型:
public class Form {
public string Field1;
public string Field2;
public Applicant PrimaryApplicant;
public Applicant SecondaryApplicant;
}
public class Applicant {
[Required(ErrorMessage = "Please enter a first name"), Display(Name = "First Name")]
public string FirstName;
[Required(ErrorMessage = "Please enter a last name"), Display(Name = "Last Name")]
public string LastName;
}
主要申请人始终是必需的,而第二申请人是可选的,除非设置了任何字段。
我尝试使用IValidatbleObject接口和Validate方法实现它,但它不起作用。 (ModelState.IsValid仍然返回false)
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var validationResult = new List<ValidationResult>();
foreach (var property in TypeDescriptor.GetProperties(this).Cast<PropertyDescriptor>())
{
Validator.TryValidateValue(property.GetValue(this), validationContext, validationResult, property.Attributes.OfType<ValidationAttribute>());
}
var validationCount = TypeDescriptor.GetProperties(this)
.Cast<PropertyDescriptor>()
.Count(p => p.Attributes.OfType<ValidationAttribute>().Any());
if (!IsPrimaryApplicant && validationResult.Count() == validationCount) validationResult.Clear();
return validationResult;
}
如何在此类情景中进行验证?