Reputation: 499
In a ASP.NET MVC4 application we are using FluentValidation for validating our models. In certain cases we only want to validate a property when another property has a value. We use the When keyword to accomplish this. A simple validation class looks like this:
public class PersonValidator : AbstractValidator<Person>
{
public PersonValidator()
{
RuleFor(item => item.FirstName).NotEmpty();
RuleFor(item => item.LastName).NotEmpty().When(item => !string.IsNullOrEmpty(item.FirstName))
}
}
We would like to have client side validation for this. I tried to create a custom FluentValidationPropertyValidator. But I can't find a way to pickup the When part of the validation rule. Can someone point me in right direction?
Upvotes: 11
Views: 7859
Reputation: 441
Fluent Validation is a server-side validation library. But It supports some basic client-validations like required, maxlength etc.
If you want to add fully client-side support to Fluent Validation, you can use Form Helper.
You need to create your forms like this:
var formConfig = new FormConfig(ViewContext)
{
FormId = "ProductForm",
FormTitle = "New Product",
BeforeSubmit = "ProductFormBeforeSubmit", // optional
Callback = "ProductFormCallback" // optional,
};
// <form id="@formConfig.FormId" asp-controller="Home" asp-action="Save"
// ...
@await Html.RenderFormScript(formConfig)
After that you need to add [FormValidator] attribute to your action.
Upvotes: 0
Reputation: 14402
FluentValidation does now support client-side validation. The following validators are supported on the client:
https://fluentvalidation.net/aspnet
Upvotes: 1
Reputation: 5747
Some of validations in FluentValidation just don't support client-side validation:
From Documentation (http://fluentvalidation.codeplex.com/wikipage?title=mvc&referringTitle=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 *Email *EqualTo (cross-property equality comparison) *Length
Upvotes: 0