sahil sahil - 4 months ago 23
C# Question

FluentValidation: how to make bool as required field with 'false' as valid input?

public bool IsDefault { get; set; }

RuleFor(stockImage => stockImage.IsDefault).NotNull();

I have this rule that "IsDefault" boolean property should be not null. The problem is when client do not pass this field when hitting the api, "IsDefault" gets default boolean property as false and do not give any error like "This field is required".

How can i make this field as required with "true" or "false" as its only valid inputs?

One solution i tried was making it:

RuleFor(stockImage => stockImage.IsDefault).NotEmpty();

The problem with this is that it gives validation error when "IsDefault" is "false" which is not expected use case.

Answer

You could use bool? (Nullable<bool>) type which is able to be null, and default value will be null.