FluentValidation : Compare value with other fields

18k views Asked by At

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.

3

There are 3 answers

0
Efanious On
RuleFor(x => x.Length).LessThanOrEqualTo(x => x.LengthMax)
   .GreaterThanOrEqualTo(x => x.LengthMin);
1
Yannick Meeus On

As per the documentation:

Note that FluentValidation will also work with ASP.NET MVC's client-side validation, but not all rules are supported. For example, any rules defined using a condition (with When/Unless), custom validators, or calls to Must will not run on the client side. The following validators are supported on the client:

*NotNull/NotEmpty
*Matches (regex)
*InclusiveBetween (range)
*CreditCard
*Email
*EqualTo (cross-property equality comparison)
*Length

There is some more information to be found regarding rolling your own fluent property validator on SO.

1
Slicksim On

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