我正在尝试使用Fluent Validation,它似乎很容易在开始时使用,但现在有一些问题。我需要验证SignIn视图模型,如下所示:
public SignInViewModelValidator(IMembershipService membershipService)
{
_membershipService = membershipService;
RuleFor(x => x.EMail).NotEmpty().EmailAddress();
RuleFor(x => x.Password).NotEmpty().Length(6, 20);
Custom(x =>
{
var user = _membershipService.ValidateUser(x.EMail, x.Password);
if (user == null)
return new ValidationFailure("EMail", "Your E-Mail Address or password was invalid.");
return null;
});
}
但是我立刻得到了所有的错误,就像这样:
当其他规则无效时,如何将此行为更改为不检查自定义验证规则?换句话说,它应该只在“电子邮件”时检查自定义验证规则。和密码'字段有效。
答案 0 :(得分:3)
我用这种方式管理了这个:
public SignInViewModelValidator(IMembershipService membershipService){
_membershipService = membershipService;
bool firstPhasePassed = true;
RuleFor(x => x.EMail)
.NotEmpty().WithMessage("")
.EmailAddress().WithMessage("")
.OnAnyFailure(x => { firstPhasePassed = false; });
RuleFor(x => x.Password)
.NotEmpty().WithMessage("")
.Length(6, 16).WithMessage("")
.OnAnyFailure(x => { firstPhasePassed = false; });
When(x => firstPhasePassed, () =>
{
Custom(x =>
{
if (_membershipService.ValidateUser(x.EMail, x.Password) == null)
return new ValidationFailure("EMail", "");
return null;
});
});
}
答案 1 :(得分:1)