user5524649
user5524649

Reputation:

Fluent Validation only if value is supplied

I have a Post method and based on the data Posted I will return a result. I want to perform validation only if the fields are supplied. If no value is posted I do not want to perform the validation. This is what I have currently. Obviously if the value is null it will crash as it expects a value, how can I solve this?

public bool IsValidAvailability(int AvailabiltyValue)
{
    if (AvailabiltyValue > AvailabilityMax || AvailabiltyValue < AvailabilityMin)
        return false;
    return true;
}

This is my Rules for the validation. Can I add anything to make this validation below happen only if the value is supplied?

RuleFor(x => (int)x.Availability).Must(validatorServices.IsValidAvailability).WithMessage("Availability must be between " + validatorServices.AvailabilityMin + " and " + validatorServices.AvailabilityMax);

Upvotes: 2

Views: 5413

Answers (1)

Omar.Alani
Omar.Alani

Reputation: 4130

You can do that through the usage of When and Unless methods.

The When and Unless methods can be used to specify conditions that control when the rule should execute. For example, this rule on the CustomerDiscount property will only execute when IsPreferredCustomer is true:

RuleFor(customer => customer.CustomerDiscount)
   .GreaterThan(0)
   .When(customer => customer.IsPreferredCustomer);

You can check the documentation here.

Upvotes: 8

Related Questions