Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 616
Sahil Sharma Avatar asked Aug 03 '16 06:08

Sahil Sharma


2 Answers

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

like image 97
Darjan Bogdan Avatar answered Sep 30 '22 22:09

Darjan Bogdan


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.

like image 34
germanpa Avatar answered Sep 30 '22 21:09

germanpa