Robin
Robin

Reputation: 517

Fluent Validation custom validation

I'd like to make 2 rules using Fluent Validation (http://fluentvalidation.codeplex.com) in my MVC project.

Nothing should happen when both Company and Name are empty. If either of them is filled, nothing should happen either. If either Company or Name is not filled, display a label at both of them. (the error message could be the same)

Ive tried this so far:

RuleFor(x => x.Name)
.NotEmpty()
.WithMessage("Please fill in the company name or the customer name")
.Unless(x => !string.IsNullOrWhiteSpace(x.Company));

RuleFor(x => x.Company)
.NotEmpty()
.WithMessage("Please fill in the company name or the customer name")
.Unless(x => !string.IsNullOrWhiteSpace(x.Name));

Ive tried combinations of When, Must and Unless, but none of them work. When i fill in nothing, no errors are shown on those 2 properties.

Can anyone help me out?

Upvotes: 4

Views: 3672

Answers (2)

Serge Belov
Serge Belov

Reputation: 5793

From the comments it seems the issue is enabling the client-side validation and the rules actually work on post-back. As specified in the FluentValidation wiki, the only supported client-side rules are

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

so essentially what you're trying to achieve is not supported out-of-the-box.

Please have a look at an example of custom client-side FluentValidation rules here.

Upvotes: 2

Artem Vyshniakov
Artem Vyshniakov

Reputation: 16465

You could add two rules with when condition:

RuleFor(x => x.Name)
.NotEmpty()
.When(x => string.IsNullOrEmpty(x.Company))
.WithMessage("Please fill in the company name or the customer name");

RuleFor(x => x.Company)
.NotEmpty()
.When(x => string.IsNullOrEmpty(x.Name))
.WithMessage("Please fill in the company name or the customer name");

Upvotes: 1

Related Questions