Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FluentValidation : Compare value with other fields

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.

like image 956
JustAspMe Avatar asked Jun 15 '15 20:06

JustAspMe


2 Answers

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

like image 150
Slicksim Avatar answered Oct 18 '22 18:10

Slicksim


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.

like image 38
Yannick Meeus Avatar answered Oct 18 '22 19:10

Yannick Meeus