我有一个我目前正在使用的解决方案。我使用Fluent 验证,但我仍然习惯它。我可以给你一个我有的简单场景的例子。也许它有帮助。我有一个用户类,具有地址对象属性。在某些时候,我只想验证用户详细信息(姓名、电子邮件、密码等),而在另一个状态下,我想验证用户地址(第一行、邮政编码等)。
类看起来像这样:
public class User {
public virtual string Name { get; set; }
public virtual string Email { get; set; }
public virtual string Password { get; set; }
public virtual Address Address { get; set; }
}
public class Address {
public virtual string Address1 { get; set; }
public virtual string PostCode { get; set; }
}
然后我有两个(简化的)验证器,一个用于地址,一个用于用户:
public AddressValidator() {
RuleFor(address => address.Address1)
.NotNull()
.WithMessage("Please enter the first line of your address");
RuleFor(address => address.PostCode)
.NotNull()
.WithMessage("Please enter your postcode")
.Matches(UK_POSTCODE_REGEX)
.WithMessage("Please enter a valid post code!");
}
public UserValidator() {
RuleFor(user => user.FirstName)
.NotNull()
.WithMessage("Please provide a first name")
.Length(3, 50)
.WithMessage("First name too short");
RuleFor(user=> user.Password)
.Length(8, 50)
.WithMessage("Password is too short");
}
然后我创建一个模型验证器,例如,假设我们有一个用户输入地址的表单,我们创建一个 AddressModelValidator,并且可以重用我们编写的验证器:
public AddressModelValidator() {
RuleFor(user => user.id)
.NotNull()
.WithMessage("An error has occured, please go back and try again");
RuleFor(user => user.Address).SetValidator(new AddressValidator());
}
因此,经过一番思考,您确实可以创建一些不错的模型,并减少验证代码的重复!