10
votes

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?

3
after some more research found out this would require a lot of work, more info: fluentvalidation.codeplex.com/discussions/229346pieter_dv

3 Answers

0
votes

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

0
votes

FluentValidation does now support client-side validation. The following validators are supported on the client:

  • NotNull/NotEmpty
  • Matches (regex)
  • InclusiveBetween (range)
  • CreditCard
  • Email
  • EqualTo (cross-property equality comparison)
  • MaxLength
  • MinLength
  • Length

https://fluentvalidation.net/aspnet

0
votes

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.