FluentValidation on number issue
I am using FluentValidation in my ASP.NET MVC 3 application.
I have a MaxNumberTeamMembers property in my view 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 ruleset is possible:
- On the front end view, if the textbox is empty then I want a "MaxNumberTeamMembers is required" message to be displayed
- If the number entered is less than 1 then I want a message to display "MaxNumberTeamMembers should be greater or equal to 1".
What would 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");
If you want to handle the empty case you need a nullable integer on your model because otherwise it is the default model binder that will automatically add a validation error when it tries to parse the empty string to a non-nullable integer:
public int? MaxNumberTeamMembers { get; set; }
and then you could have the following validation rules on 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");
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");
it is work with FluentValidation version 3.2
RuleFor(x => x.MaxNumberTeamMembers)
.NotNull()
.WithMessage("Please Enter Value")
.InclusiveBetween(1, 500)
.WithMessage("Value must be number Beetween 1 , 500");
精彩评论