假设你有一个 viewModel:
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; }
}
还有型号Address
看起来像这样:
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 创建一个视图模型并在其中添加一些自定义逻辑,但我需要一个实例Address
传递到我的 EditorTemplate 的地址。
这里的主要问题是地址的验证是在我的 PersonViewModel 的验证之前完成的,所以我无法阻止它。
注意:RequiredIfAttribute 是一个自定义属性,它正好满足我对简单类型的需求。
如果你使用过的话,那就小菜一碟了FluentValidation.NET http://fluentvalidation.codeplex.com/而不是 DataAnnotations 或 IValidatableObject 在复杂场景中相当限制验证能力:
public class CreatePersonViewModelValidator : AbstractValidator<CreatePersonViewModel>
{
public CreatePersonViewModelValidator()
{
RuleFor(x => x.Address)
.SetValidator(new AddressValidator())
.When(x => x.HasDeliveryAddress);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)