首页  >  文章  >  后端开发  >  如何使用 Fluent Validation 检查 C# 中属性的最小长度和最大长度验证?

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

PHPz
PHPz转载
2023-08-25 12:13:05726浏览

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

MaxLength 验证器

确保特定字符串属性的长度不超过指定值。

仅对字符串属性有效

字符串格式参数:

{PropertyName} = 属性的名称正在验证

{MaxLength} = 最大长度

{TotalLength} = 输入的字符数

{PropertyValue} = 属性的当前值

MinLength 验证器

确保特定字符串属性的长度大于指定值。

仅对字符串属性有效

{PropertyName} = 正在验证的属性名称

{MinLength} = 最小长度

{TotalLength} = 输入的字符数

{PropertyValue} = 当前财产的价值

示例

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}");
   }
}

输出

MaximumLength must be 7 First Name
MinimumLength must be 5 Last Name

以上是如何使用 Fluent Validation 检查 C# 中属性的最小长度和最大长度验证?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:tutorialspoint.com。如有侵权,请联系admin@php.cn删除