Hi Guys,
In my project I need to implement a conditional variable to a Rule. Imagine, Rule B can only run if the Rule A does not fail, How do you achieve it today? What I've done is, I created a class called ValidationResultHolder and inside this class a property IsValid. Then In my property validator extension I pass it in the constructor and get the result after the Rule is executed. For example:
In my project I need to implement a conditional variable to a Rule. Imagine, Rule B can only run if the Rule A does not fail, How do you achieve it today? What I've done is, I created a class called ValidationResultHolder and inside this class a property IsValid. Then In my property validator extension I pass it in the constructor and get the result after the Rule is executed. For example:
var validVehicle = new ValidationResultHolder();
RuleFor(v => v)
.MustBeAValidVehicle(validVehicle)
.WithName("Vehicle")
.Unless(v => v.MakeId == null || v.ModelId == null && v.Year == default(short));
RuleFor(v => v.VehicleVin)
.MustBeAValidVehicleVin()
.When(v => validVehicle.IsValid);
In addition I downloaded the source code and added an overload for each default property validator which is implemented.public static IRuleBuilderOptions<T, TProperty> NotNull<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder, ValidationResultHolder valid)
{
return ruleBuilder.SetValidator(new NotNullValidator(valid));
}
public class NotNullValidator : PropertyValidator, INotNullValidator {
readonly ValidationResultHolder validationResultHolder;
public NotNullValidator()
: base(() => Messages.notnull_error)
{
validationResultHolder = new ValidationResultHolder();
}
public NotNullValidator(ValidationResultHolder valid)
: base(() => Messages.notnull_error)
{
validationResultHolder = valid;
}
protected override bool IsValid(PropertyValidatorContext context)
{
validationResultHolder.IsValid = context.PropertyValue != null;
return validationResultHolder.IsValid;
}
}
I think it should be considered as a new feature to Fluent Validation.