假设您有一个viewModel: public class CreatePersonViewModel{ [Required] public bool HasDeliveryAddress {get;set;} // Should only be validated when HasDeliveryAddress is true [RequiredIf("HasDeliveryAddress", true)] public Address Addr
public class CreatePersonViewModel { [Required] public bool HasDeliveryAddress {get;set;} // Should only be validated when HasDeliveryAddress is true [RequiredIf("HasDeliveryAddress", true)] public Address Address { get; set; } }
模型地址将如下所示:
public class Address : IValidatableObject { [Required] public string City { get; set; } [Required] public string HouseNr { get; set; } [Required] public string CountryCode { get; set; } [Required] public string FirstName { get; set; } [Required] public string LastName { get; set; } [Required] public string ZipCode { get; set; } [Required] public string Street { get; set; } #region IValidatableObject Members public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { string[] requiredFields; var results = new List<ValidationResult>(); // some custom validations here (I removed them to keep it simple) return results; } #endregion }
有些人会建议为Address创建一个viewmodel并在那里添加一些自定义逻辑,但我需要一个Address实例传递给我的EditorTemplate for Address.
这里的主要问题是Address的验证是在我的PersonViewModel验证之前完成的,所以我无法阻止它.
注意:RequiredIfAttribute是一个自定义属性,它可以完成我想要的简单类型.
如果您使用 FluentValidation.NET而不是DataAnnotations或IValidatableObject,在复杂的情况下会严重限制验证功能,那本来就是小菜一碟:public class CreatePersonViewModelValidator : AbstractValidator<CreatePersonViewModel> { public CreatePersonViewModelValidator() { RuleFor(x => x.Address) .SetValidator(new AddressValidator()) .When(x => x.HasDeliveryAddress); } }