Free validation check

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

Nothing should happen when both companies and name are empty. If any of them are full, nothing should happen. If neither the company nor the name is empty, display a label on them. (error message may be the same)

I have 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 to combine When, Must and Unless, but none of them work. When I fill nothing, errors are not displayed on these 2 properties.

Can anyone help me out?

+4
source share
2 answers

From the comments, the problem seems to be that client side validation and rules do work on the back side. As stated in the FluentValidation wiki , the only client-side rules supported are

  • NotNull / NotEmpty
  • Matches (regular expression)
  • InclusiveBetween (range)
  • Creditcard
  • Email
  • EqualTo (comparison of comparisons between properties)
  • Length

so essentially what you are trying to achieve is not supported out of the box.

Please see a sample client-side FluentValidation rules here .

+2
source

You can add two rules with a 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"); 
0
source

Source: https://habr.com/ru/post/1443233/


All Articles