Question

I am trying to use Fluent Validation and it seems easy to use at the beginning but now there is some problem. I need to validate a SignIn view model, shown below:

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;
        });
    }

But I'm getting all the errors at once, like this:

  • 'E Mail' should not be empty.
  • Your E-Mail Address or password was invalid.
  • 'Password' should not be empty.

How can I change this behavior to not check the Custom validation rule when the other rules are invalid? In other words, it should only check the Custom validation rule when 'EMail' and 'Password' fields are valid.

Was it helpful?

Solution

I managed this in this way:

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;
    });
});

}

OTHER TIPS

You can use the When method to check your custom rule only when your email/password rules are valid.

To make this easier, I suggest moving your Custom rule logic into a separate method (something like IsValidEmailAndPassword) and use the Must method to validate both email and password. Since you're passing in multiple parameters (email and password) into that method, read the documentation on the overload of Must that "accepts an instance of the parent object being validated" in order to implement this rule.

Hopefully those links point you to the right direction.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top