Home > Backend Development > C#.Net Tutorial > How to check minimum and maximum length validation of properties in C# using Fluent Validation?

How to check minimum and maximum length validation of properties in C# using Fluent Validation?

PHPz
Release: 2023-08-25 12:13:05
forward
838 people have browsed it

如何使用 Fluent Validation 检查 C# 中属性的最小长度和最大长度验证?

MaxLength Validator

Ensures that the length of a particular string property is no longer than the specified value.

Only valid on string properties

String format args:

{PropertyName} = The name of the property being validated

{MaxLength} = Maximum length

{TotalLength} = Number of characters entered

{PropertyValue} = The current value of the property

MinLength Validator

Ensures that the length of a particular string property is longer than the specified value.

Only valid on string properties

{PropertyName} = The name of the property being validated

{MinLength} = Minimum length

{TotalLength} = Number of characters entered

{PropertyValue} = The current value of the property

Example

static void Main(string[] args){
   List errors = new List();

   PersonModel person = new PersonModel();
   person.FirstName = "TestUser444";
   person.LastName = "TTT";

   PersonValidator validator = new PersonValidator();
   ValidationResult results = validator.Validate(person);

   if (results.IsValid == false){
      foreach (ValidationFailure failure in results.Errors){
         errors.Add(failure.ErrorMessage);
      }
   }

   foreach (var item in errors){
      Console.WriteLine(item);
   }
   Console.ReadLine();
   }
}
public class PersonModel{
   public string FirstName { get; set; }
   public string LastName { get; set; }
}
public class PersonValidator : AbstractValidator{
   public PersonValidator(){
      RuleFor(p => p.FirstName).MaximumLength(7).WithMessage("MaximumLength must be 7 {PropertyName}") ;
      RuleFor(p => p.LastName).MinimumLength(5).WithMessage("MinimumLength must be 5 {PropertyName}");
   }
}
Copy after login

输出

MaximumLength must be 7 First Name
MinimumLength must be 5 Last Name
Copy after login

The above is the detailed content of How to check minimum and maximum length validation of properties in C# using Fluent Validation?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template