-
Notifications
You must be signed in to change notification settings - Fork 11
PropertyValidators: Conditions
If you want that one check is executed only with certain condition, you can use When
method:
builder.RuleFor(vm => vm.Email)
.NotEmpty()
.When(vm => PhoneNumber, phoneNumber => string.IsNullOrEmpty(phoneNumber))
.Must(IsValidEmail);
In this case, it's possible to have empty Email
when property PhoneNumber
is not empty (we check NotEmpty
only if PhoneNumber
is empty). This rule will be revalidated each time when PhoneNumber
changed. So if you enter phone number and then deleted it -> property Email
will be not valid.
If you want that all checks are executed only with certain condition, you can use AllWhen
method:
builder.RuleFor(vm => vm.Country)
.NotEmpty()
.MaxLength(64)
.AllWhen(vm => vm.ShouldSpecifyAdditionalInformation);
In this case property Country
can have any value if property ShouldSpecifyAdditionalInformation == false
.
There are few overloading of methods When
and AllWhen
, but you can create your own with interface ReactiveValidation.Validators.Conditions.IValidationCondition
.
If your condition connected with some other properties, their expressions should be at IValidationCondition.RelatedProperties
.
You can use FuncValidationCondition as sample.