0

I have this rule for validate that a property has a valid value depending on a list of allowed values in another property.

model.RuleFor(c => c)
.Must(c => string.IsNullOrEmpty(c.CurrentValue) || (!string.IsNullOrEmpty(c.CurrentValue) && c.AllowedValues.Contains(c.CurrentValue)))

That works fine, but I want to create a unit test, but always fail. I think is because of the RuleFor is not at an specific property but the object itself.

this.validator.ShouldNotHaveValidationErrorFor(c => c.CurrentValue, this.model);

How can I improve the validator or the test?

Gabriel Castillo Prada
  • 4,114
  • 4
  • 21
  • 31

1 Answers1

0

You can use a Custom validation, so that you can tie the validation failure to a specific property:

model.RuleFor(c => c.CurrentValue).NotEmpty();

model.When(c => !string.IsNullOrEmpty(c.CurrentValue), () => Custom(CurrentValueIsAllowed));

private ValidationFailure CurrentValueIsAllowed(YourModelType c)
{
    if(c.AllowedValues.Contains(c.CurrentValue))
    {
        return null;
    } 

    return new ValidationFailure("CurrentValue", "Value is not allowed.");
}
Pedro
  • 2,300
  • 1
  • 18
  • 22