14

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.

SSH
  • 1,609
  • 2
  • 22
  • 42
JustAspMe
  • 418
  • 1
  • 4
  • 18

3 Answers3

30

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

Slicksim
  • 7,054
  • 28
  • 32
  • 1
    The **reason** I'm using this is for the JavaScript validation. Possibly I can just manually add the JavaScript validation myself and use Must. I'll investigate this option, thanks. – JustAspMe Jul 10 '15 at 17:54
3

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.

Yannick Meeus
  • 5,643
  • 1
  • 35
  • 34
  • I have been looking through the documentation but was hoping someone has already done something similar and could provide a sample. Thanks, I will be look through the docs. – JustAspMe Jul 10 '15 at 17:55
1
RuleFor(x => x.Length).LessThanOrEqualTo(x => x.LengthMax)
   .GreaterThanOrEqualTo(x => x.LengthMin);
Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77
Efanious
  • 11
  • 3