Is it possible to pass a value into the error message. I have tried something like this:
RuleFor(x => x.ForeName).Length(1, 255).WithLocalizedMessage(() => String.Format(ValidationErrors.TooLong, "255"));
ValidationErrors is my resource file which contains:
TooLong Please use fewer than {0} characters.
This:
RuleFor(x => x.ForeName).Length(1, 255).WithLocalizedMessage(() => ValidationErrors.TooLong);
works fine.
FluentValidation is a server-side library and does not provide any client-side validation directly. However, it can provide metadata which can be applied to the generated HTML elements for use with a client-side framework such as jQuery Validate in the same way that ASP. NET's default validation attributes work.
There is no way to debug Fluent Validator code with Visual Studio tools. You need to comment the specific part of code (RuleFor) that you want to test. Keep doing it until all rules are tested.
FluentValidation provides a great alternative to Data Annotations in order to validate our models. As we've seen, the validation rules are easy to read, easy to test, and enable great separation of concerns keeping our controllers lightweight.
FluentValidation is a .NET library for building strongly-typed validation rules. It Uses a fluent interface and lambda expressions for building validation rules. It helps clean up your domain code and make it more cohesive, as well as giving you a single place to look for validation logic.
With the currently released version of FluentValidation (v2), this isn't supported when using localized messages.
The first argument to WithLocalizedMessage must always identify a resource property - you can't place arbitrary code inside there (such as a call to string.format).
If you're using a non-localized message then you can do this:
RuleFor(x => x.Property).Length(1,255).WithMessage("Max number of chars is {0}", "255");
You'll also be able to use this approach with localized error messages as of FluentValidation v3, but there's no binary release yet so if you want to make use of this then you could grab and build the source from the project site.
As an alternative, instead of using numerical placeholders you can use FV's built in support for named placeholders for the default validators. So if you're using .Length(1, 255) then you can use {MaxLength} inside your error message instead of {0}:
Please use fewer than {MaxLength} characters.
...and FV will automatically replace this with the value you entered as the maximum. There's a full list of all the named placeholders in the documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With