I have two properties in a class which are dependent on one another:
public class SomeClass
{
public DateTime EarliestDeliveryDate { get; set; }
public DateTime LatestDeliveryDate { get; set; }
...
}
I configured the FluentValidation as follows:
using FluentValidation;
...
public class SomeValidator : AbstractValidator<SomeClass>
{
public SomeValidator ()
{
RuleFor(x => x.EarliestDeliveryDate).Must((order, earliestDeliveryDate) => earliestDeliveryDate < order.LatestDeliveryDate)
.WithMessage("Earliest delivery date has to be before the latest delivery date.");
RuleFor(x => x.LatestDeliveryDate)
.Must((order, latestDeliveryDate) => latestDeliveryDate > order.EarliestDeliveryDate)
.WithMessage("Latest delivery date has to be after the earliest delivery date.");
...
}
}
The validation for each property works as expected. However if the user enters an invalid date for both properties, then corrects one of the input fields (let's say EarliestDeliveryDate), the error message for the other property (e. g. LatestDeliveryDate) remains.
How to trigger the validation for all dependent properties, if the value of one property changes?
My recommendation would be to have you model class implement INotifyPropertyChanged
interface and then raise the event in the Setter of all related properties like so:
public int LocationId
{
get => locationId;
set
{
locationId = value;
NotifyPropertyChanged(nameof(LocationId));
if (HazardId != default && MeasuredPersianDate != default)
{
NotifyPropertyChanged(nameof(HazardId));
NotifyPropertyChanged(nameof(MeasuredPersianDate));
}
}
}
This way,if your UI is a framework like WPF or Xamarin Forms,as one of the related properties change,the validation will be triggered for the other ones as well automatically.However,If your UI framework doesn't refresh the view automatically when a NotifyPropertyChanged
is raised,you need to subscribe to the event and have the UI trigger the validation for the related properties.For example in Blazor you can use the following code:
model.PropertyChanged +=
(object sender, System.ComponentModel.PropertyChangedEventArgs e) =>
{
if (e.PropertyName is null) return;
form.EditContext!.NotifyFieldChanged(form.EditContext.Field(e.PropertyName));
};
where form
is the variable referring to the EditForm by using @ref
<EditForm @ref="form" Context="ctx" Model="model"OnValidSubmit="SaveChanges">...</EditForm>