FluentValidation by Release Number

I am using FluentValidation in my ASP.NET MVC 3 application.

I have a MaxNumberTeamMembers property in my model as such:

/// <summary> /// Gets or sets the maximum number of team members. /// </summary> public int MaxNumberTeamMembers { get; set; } 

I want to know if the following rule set is possible:

  • In the front panel view, if the text box is empty, I want the message "MaxNumberTeamMembers" to be displayed.
  • If the number entered is less than 1, then I want the message to display "Max. Number. Members must be greater than or equal to 1".

What will the ruleset for the above look like?

I have the following, but it does not work on the GreaterThan part if I enter 0:

 RuleFor(x => x.MaxNumberTeamMembers) .NotEmpty() .WithMessage("Max. number of team members is required") .GreaterThan(0) .WithMessage("Max. number of team members must be greater than 0"); 

UPDATE 2011-02-14:

 RuleFor(x => x.MinNumberCharactersCitation) .NotNull() .WithMessage("Min. number of characters for citation is required") .GreaterThanOrEqualTo(1) .WithMessage("Min. number of characters for citation must be greater than or equal to 1") .LessThanOrEqualTo(x => x.MaxNumberCharactersCitation) .WithMessage("Min. number of characters must be less than or equal to max. number of characters"); 
+4
source share
2 answers

If you want to handle an empty case, you will need a zero integer on your model, because otherwise it is the default connecting device that will automatically add a validation error when it tries to parse an empty string into a non-nullable integer:

 public int? MaxNumberTeamMembers { get; set; } 

and then you can have the following rules for checking this property:

 RuleFor(x => x.MaxNumberTeamMembers) .NotEmpty() .WithMessage("Max. number of team members is required") .Must(x => x.Value > 0) .When(x => x.MaxNumberTeamMembers != null) .WithMessage("Max. number of team members must be greater than 0"); 

Strike>


UPDATE:

The following works fine with the latest version of FluentValidation:

 RuleFor(x => x.MaxNumberTeamMembers) .NotNull() .WithMessage("Max. number of team members is required") .GreaterThan(0) .WithMessage("Max. number of team members must be greater than 0"); 
+5
source

this is working with version 3.2 of FluentValidation

 RuleFor(x => x.MaxNumberTeamMembers) .NotNull() .WithMessage("Please Enter Value") .InclusiveBetween(1, 500) .WithMessage("Value must be number Beetween 1 , 500"); 
0
source

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


All Articles