1

I use Fluent Validation .NET for validating. Is it possible to determine error messages sequence from "RuleFor" in validation summary.

Example:

RuleFor(x=>x.A).NotEmpty().WithMessage("A is required.");
RuleFor(x=>x.B).NotEmpty().WithMessage("B is required.");

For example, How can I determine message sequence to specificly show "B is required." before "A is required".

LLF
  • 668
  • 3
  • 10
  • 27
  • Can you describe in details, which behavior you want to see? Same messages for different rules, or message for B, that depends on A value, or something else? – David Levin May 11 '15 at 09:54
  • I added some more detail about question. I just want to sort the message that display on Summary Validation Message. – LLF May 11 '15 at 10:45

1 Answers1

1

There is no explicit ordering of rules inside FluentValidationModelValidationFactory validator queries, that means that order of error messages on server-side depends on order of rules declaration, e.g. if rule for A property goes before rule for B, then you will see in ValidationResult error message for A before B. But it works only for manually getting of validation result (create validator object and call Validate method).

After errors get into ModelState object - they loss their order. Thats because of ModelStateDictionary type, which stores objects as Dictionary, not as List.

And if we look at NDoc description of ValidationSummary method, we see:

Returns an unordered list (ul element) of validation messages that are in the ModelStateDictionary object.

But if client-side validation enabled - then validation summary element appears without server call, and it's error messages order the same as order of inputs in html.

Conclusion The only way to save error message order in ViewResult is to 'manually' use validator, call validate and manually iterate ValidationResult in partial view or template to create markup you need. But if you rely on client-side validation — you can just reoder inputs on form.

David Levin
  • 6,573
  • 5
  • 48
  • 80