Search code examples
c#asp.net-corefluentvalidation

Fluent Validation Boolean field must be required


The below code is not giving me error Saying 'isContinuous' is required field.

public class Bond
{
  public bool isContinuous { get; set; }
}

public class BondValidator : AbstractValidator<Bond>
{
    public BondValidator()
    {
        RuleFor(model => model.isContinuous).NotNull().WithMessage("'is Continous' is required field.").Must(x => x == false || x == true);
            
    }
}          

Solution

  • bool is a value type, it always is not null. One option is to change the type to be nullable value type - bool?:

    public class Bond
    {
        public bool? isContinuous { get; set; }
    }
    

    Then the null check will make sense.

    Alternatively you can try using required modifier (available since C# 11), but it should result in error on the binder/deserializer level before the fluent validation.

    Read more: