如何使用 Fluent Validation 在 C# 中檢查屬性的 Minlength 和 Maxlength 驗證?
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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP