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

2023年 8月 27日 60.5k 0

如何使用 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}");
}
}

登录后复制

输出

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

登录后复制

以上就是如何使用 Fluent Validation 检查 C# 中属性的最小长度和最大长度验证?的详细内容,更多请关注每日运维网(www.mryunwei.com)其它相关文章!

相关文章

JavaScript2024新功能:Object.groupBy、正则表达式v标志
PHP trim 函数对多字节字符的使用和限制
新函数 json_validate() 、randomizer 类扩展…20 个PHP 8.3 新特性全面解析
使用HTMX为WordPress增效:如何在不使用复杂框架的情况下增强平台功能
为React 19做准备:WordPress 6.6用户指南
如何删除WordPress中的所有评论

发布评论