Sahil Sharma
Sahil Sharma

Reputation: 4217

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.

Upvotes: 17

Views: 28659

Answers (3)

germanpa
germanpa

Reputation: 371

You could use this:

RuleFor(stockImage => stockImage.IsDefault).Must(x => x == false || x == true)

from the c# perspective doesn't make sense, because the bool value always be true or false but if the data come from an api, value can be anything different like '' or null and you don't have to change your model.

Upvotes: 21

Darjan Bogdan
Darjan Bogdan

Reputation: 3900

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

Upvotes: 21

Guy haimovitz
Guy haimovitz

Reputation: 1625

Just declare an enum called booleanType with the fields {false,true,null}

Use the new type instead of c# bool type initially set to null.

Upvotes: -10

Related Questions