Search code examples
c#fluentvalidation

FluentValidator isInEnum Not validate for first item


I have a fluent validator:

 public MyValidator()
        {
            RuleFor(t => t.Gender)
                .IsInEnum()
                .NotEmpty();
            //...
        }

Gender is enum type

public enum Gender
  {
    NotSpecified,
    Male,
    Female,
  }

test method for all enum values

[Theory]
[InlineData(Gender.NotSpecified)]
[InlineData(Gender.Female)]
[InlineData(Gender.Male)]
public void WhenGenderIsInEnum_ShouldValidate(Gender gender)
{
    // Arrange
    var model = new MyObject {Gender = gender};

    // Act
    var result = _validator.TestValidate(model);

    // Assert
    result
        .ShouldNotHaveValidationErrorFor(s => s.Gender);
}

test for male and female are ok, but for fist item 'NotSpecified' it return an error

Validation Errors:
[0]: 'Gender' must not be empty.

any ideas?


Solution

  • Maybe its because the NotSpecified enum is automatically assigned value 0 and the fluent validator checks if the value == default

    Try changing the value type to nullable.