Reputation: 500
I have been unsuccessful in implementing case insensitive comparing using Fluent Validations. I am just trying to compare two email fields and ignoring case.
The rules in place currently are:
RuleFor(x => x.EmailAddress).NotEmpty().Length(5, 200).EmailAddress();
RuleFor(x => x.ConfirmEmailAddress).NotEmpty().Equal(x => x.EmailAddress).WithMessage("Emails must match");
To add the requirement to be case insensitive I considered passing a comparer with the equal call but that does not seem to work.
RuleFor(x => x.ConfirmEmailAddress).NotEmpty().Equal(x => x.EmailAddress, StringComparer.CurrentCultureIgnoreCase).WithMessage("Emails must match");
Ideally, I would like to have a case insensitive comparison done on client side if possible. Will anyone be able to provide guidance on how to accomplish this?
The NuGet packages I am currently using are:
<package id="FluentValidation" version="5.1.0.0" targetFramework="net45" />
<package id="FluentValidation.MVC4" version="5.1.0.0" targetFramework="net45" />
Upvotes: 4
Views: 4731
Reputation: 5910
You can make use of the .Must() extension method, with the overload that accepts both the parent object and the property being validated like so:
RuleFor(x => x.ConfirmEmailAddress)
.NotEmpty()
.Must((x, confirmEmailAddress) => x.EmailAddress.Equals(confirmEmailAddress, StringComparison.OrdinalIgnoreCase))
.WithMessage("Emails must match");
This is only supported on the server-side, however, 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
- EqualTo (cross-property equality comparison)
- Length
Upvotes: 5