Reputation: 5105
I'm developing an ASP.Net MVC 5 web application and I'm using FluentValidation (https://github.com/JeremySkinner/FluentValidation) for validation. I am having trouble with the .When() clause in that I can't get it working. However, I can get the likes of the .NotEmpty() and .Length() clauses working.
This is my Viewmodel class
[Validator(typeof(ViewModelEmployerValidator))]
public class ViewModelEmployer
{
public string CurrentLineManagerEmail { get; set; }
public string NewLineManagerEmail { get; set; }
}
public class ViewModelEmployerValidator : AbstractValidator<ViewModelEmployer>
{
public ViewModelEmployerValidator()
{
RuleFor(x => x.NewLineManagerEmail).NotEmpty().When(x => x.CurrentLineManagerEmail == "").WithMessage("Please enter your new Line Manager Email");
}
}
My Razor View
<div>
<div class="form-group">
@Html.TextBoxFor(model => model.CurrentLineManagerEmail, new { @class = "form-control", placeholder = "Current Line Manager Email" })
@Html.ValidationMessageFor(model => model.CurrentLineManagerEmail)
</div>
</div>
<div>
<div class="form-group">
@Html.TextBoxFor(model => model.NewLineManagerEmail, new { @class = "form-control", placeholder = "New Line Manager Email" })
@Html.ValidationMessageFor(model => model.NewLineManagerEmail)
</div>
</div>
When the user submits the form, even when the text box CurrentLineManagerEmail is left empty, the .When() validation does that pick up the rule and ask the user to enter their new line manager email.
However, as stated above, the likes of .NotEmpty() and .Length() or their own work fine. It's only when I add the .When() clause that the validation seems to fail.
Can anyone please help?
Thanks.
Upvotes: 3
Views: 2745
Reputation: 29243
FluentValidation has limited support for client-side validation:
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
(From https://fluentvalidation.codeplex.com/wikipage?title=mvc)
Upvotes: 2