[英]FluentValidation IRuleBuilderOptions extension method - only run regex validator if value exists
我有以下用於驗證電話號碼的 FluentValidation 擴展方法:
public static IRuleBuilderOptions<T, string> MatchPhoneNumber<T>(this IRuleBuilder<T, string> rule)
=> rule.Matches(@"^(1-)?\d{3}-\d{3}-\d{4}$").WithMessage("Invalid phone number");
我稱之為:
RuleFor(contact => contact.PhoneNumber).MatchPhoneNumber()
但是,我只希望擴展方法在電話號碼字符串不為空/空時驗證電話號碼。 我可以通過執行以下操作來做到這一點:
RuleFor(contact => contact.PhoneNumber)
.MatchPhoneNumber()
.When(contact => !string.IsNullOrEmpty(contact.PhoneNumber));
但是有沒有辦法可以在擴展方法本身中做到這一點?
您可以更改您的正則表達式以接受這樣的空字符串: ^$|^(1-)?\d{3}-\d{3}-\d{4}$
但是,我嘗試了最新版本的 FluentValidation (10.3.3),如果您將 null 或空字符串傳遞給Matches
規則,它不會給出任何錯誤。 在我的示例代碼中,盡管 PhoneNumber 為 Null,但結果中沒有任何錯誤:
class Program
{
static void Main(string[] args)
{
var contact = new Contact();
var contactValidator = new ContactValidator();
var result = contactValidator.Validate(contact);
Console.WriteLine(result.IsValid); // This returns true with null phone number
}
}
public class Contact
{
public string PhoneNumber { get; set; }
}
public class ContactValidator : AbstractValidator<Contact>
{
public ContactValidator()
{
RuleFor(contact => contact.PhoneNumber)
.MatchPhoneNumber();
}
}
public static class Extensions
{
public static IRuleBuilderOptions<T, string> MatchPhoneNumber<T>(this IRuleBuilder<T, string> rule)
=> rule.Matches(@"^(1-)?\d{3}-\d{3}-\d{4}$").WithMessage("Invalid phone number");
}
您是否使用不同的方式來定義您的驗證器?
public static class Extensions
{
public static IRuleBuilderOptions<T, string> MatchPhoneNumber<T>(this IRuleBuilder<T, string> rule, Func<T, bool> expression)
=> rule.Matches(@"^(1-)?\d{3}-\d{3}-\d{4}$").WithMessage("Invalid phone number").When(expression);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.