How to chain FluentApi validation

Viewed 29

I have issue with FluentApiValidation.

Example:

RuleFor(x => x.IdentificationNumber)
    .Matches("^\\d{8}$").When(x => x.IsLegalType).WithMessage("This validation occurs only if this row is present, but not if other rows below are presented.")
    .Matches("^\\d{13}$").When(x => !x.IsLegalType).WithMessage("This validation always works")
    .Must((model, identificationNumber) => BeUniqueForIdentificationNumber(model)).WithMessage("This Validation Always works")
    .NotNull().WithMessage("This validation always works!");

Flag IsLegalType works correctly, but for some reason, the first chain block validation does not work, when I put other chains after.

If I comment all below chains and just put:

RuleFor(x => x.IdentificationNumber)
    .Matches("^\\d{8}$").When(x => x.IsLegalType).WithMessage("This validation occurs only if this row is present, but not if other rows below are presented.");

I believe that I need to change chaining in a better way. Any hints?

1 Answers

You want to create a new Rule for each validation scenario.

     RuleFor(x => x.IdentificationNumber)
        .Matches("^\\d{8}$").When(x => x.IsLegalType).WithMessage("This validation occurs only if this row is present, but not if other rows below are presented.");
     RuleFor(x => x.IdentificationNumber)
         .Matches("^\\d{13}$").When(x => !x.IsLegalType).WithMessage("This validation always works");
     RuleFor(x => x.IdentificationNumber)
         .Must((model, identificationNumber) => BeUniqueForIdentificationNumber(model)).WithMessage("This Validation Always works");
     RuleFor(x => x.IdentificationNumber)
         .NotNull().WithMessage("This validation always works!");
Related