如何使用Fluent验证检查C#中属性的最小长度和最大长度验证?
MaxLength验证器
确保特定字符串属性的长度不超过指定值。
仅对字符串属性有效
字符串格式参数:
{PropertyName}=要验证的属性的名称
{MaxLength}=最大长度
{TotalLength}=输入的字符数
{PropertyValue}=属性的当前值
最小长度验证器
确保特定字符串属性的长度大于指定的值。
仅对字符串属性有效
{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
热门推荐
10 毛笔哥哥结婚祝福语简短
11 向国庆送祝福语简短
12 建队节祝福语简短
13 朋友喜得外孙简短祝福语
14 小店营业的祝福语简短
15 餐饮生日祝福语简短独特
16 鲜花英语祝福语卡片简短
17 男朋友暴富祝福语简短
18 婶婶拜年祝福语大全简短