使用Fluent验证进行条件登录验证

时间:2013-08-04 13:28:20

标签: asp.net-mvc-4 fluentvalidation

我正在尝试使用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;
        });
    }

但是我立刻得到了所有的错误,就像这样:

  • ' E Mail'不应该是空的。
  • 您的电子邮件地址或密码无效。
  • '密码'不应该是空的。

当其他规则无效时,如何将此行为更改为检查自定义验证规则?换句话说,它应该只在“电子邮件”时检查自定义验证规则。和密码'字段有效。

2 个答案:

答案 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)

只有在您的电子邮件/密码规则有效时,才能使用When方法检查自定义规则。

为了简化这一过程,我建议将自定义规则逻辑移动到单独的方法(类似IsValidEmailAndPassword),并使用Must方法验证电子邮件和密码。由于您将多个参数(电子邮件和密码)传递到该方法,因此请阅读Must的重载文档,该文档“接受正在验证的父对象的实例”,以便实现此规则。

希望这些链接指向正确的方向。