简体   繁体   中英

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.

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM