问题
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".
回答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.
来源:https://stackoverflow.com/questions/30163606/can-fluent-validation-net-determine-error-messages-sequence