FluentValidation : Compare value with other fields

JustAspMe picture JustAspMe · Jun 15, 2015 · Viewed 7.4k times · Source

I was referred to using FluentValidation for use in MVC5 C# ASP.NET. I am trying to compare a field to two other fields but am getting an error.

The code in my customized "AbstractValidator" is the following :

RuleFor(x => x.Length).LessThanOrEqualTo(y => y.LengthMax)
   .GreaterThanOrEqualTo(z => z.LengthMin);

And when the view tried to render the control for the "Length" field using EditFor() this error displays...

Additional information: Validation type names in unobtrusive client validation rules must be unique. The following validation type was seen more than once: range

How would one go about comparing one value to two other values of the same model.

Answer

Slicksim picture Slicksim · Jul 10, 2015

If you don't mind losing the javascript validation, you can do it using the Must extension of FluentValidation

RuleFor(m=> m.Length).Must((model, field) => field >= model.LengthMin && field <= model.LengthMax);

HTH