-
Notifications
You must be signed in to change notification settings - Fork 11
Delay before validation (property throttling)
Works only in 2.0.3+ version
In normal mode, each time when property changed its value, then check all connected validation rules. But if property value changes very fast (for example, typing email address in TextBox
) and validation rules take some time, it may cause freezes.
In these cases, it's better to wait until property stops changing for a while and call validation only after it (for example, after user stops typing his email address). It's possible to set up such delay using Throttle
and CommonThrottle
construction.
You can create delay for one validation rule:
builder.RuleFor(vm => vm.Email)
.NotEmpty()
.Must(IsValidEmail).Throttle(1000);
In this case, NotEmpty()
will check each time, but Must(IsValidEmail)
only if Email
value wasn't changed during 1 second.
Also, possible setup delay for whole property:
builder.RuleFor(vm => vm.PhoneNumber)
.NotEmpty()
.Matches(@"^\d{11}$")
.CommonThrottle(2000);
In this case, NotEmpty()
and Matches(@"^\d{11}$")
will check only if PhoneNumber
value wasn't changed during 2 seconds.
Next methods work only with property in RuleFor
:
Throttle(int validatingPropertyMillisecondsDelay);
Throttle(TimeSpan validatingPropertyDueTime);
CommonThrottle(int validatingPropertyMillisecondsDelay);
CommonThrottle(TimeSpan validatingPropertyDueTime);
When you need to have delay for related properties, use throttleBuilder
:
builder.RuleFor(vm => vm.Email)
.NotEmpty()
.Must(IsValidEmail)
.AllWhen(vm => vm.IsEmailEnabled)
.CommonThrottle(throttleBuilder => throttleBuilder
.AddValidatingPropertyThrottle(1000)
.AddRelatedPropertyThrottle(vm => vm.IsEmailEnabled, 3000));
In this case, you can specify delay for each property separately.
- Throttling is based on async validators (even if you use sync validation, it becomes async). Because of that, you should wait async validation completeness in your code.
- Calling
IObjectValidator.WaitValidatingCompletedAsync
doesn't skip throttle. Be careful with delay duration.
You can override interface ReactiveValidation.Validators.Throttle.IPropertiesThrottle
and create your own realization. Default realization: PropertiesThrottle