代码之家  ›  专栏  ›  技术社区  ›  Hina Khuman Santosh Pillai

使用fluent validation ASP.NET Core WebApi进行正则表达式验证

  •  0
  • Hina Khuman Santosh Pillai  · 技术社区  · 7 年前

    我正在使用WebApi项目并使用fluent验证来验证请求。

    用户基础Dto。

    public class UserBaseDto
    {    
        [JsonProperty("email")]
        public string Email { get; set; }
    
        [JsonProperty("countryId")]
        public int CountryId { get; set; }
    
        [JsonProperty("phoneNumber")]
        public string PhoneNumber { get; set; }
    }
    

    用户注册Dto。

    public class RegisterDto : UserBaseDto
    {
    }
    

    基于用户的虚拟机。

    public class UserBaseDtoValidator : AbstractValidator<UserBaseDto>
    {
        public UserBaseDtoValidator()
        {            
            RuleFor(x => x.Email)
                .EmailAddress()
                .WithMessage("Please provide valid email");
    
            RuleFor(x => x.PhoneNumber)
                .MatchPhoneNumberRule()
                .WithMessage("Please provide valid phone number");
        }
    }
    

    MatchPhoneNumberRule 是自定义验证程序

    public static class CustomValidators
    {
        public static IRuleBuilderOptions<T, string> MatchPhoneNumberRule<T>(this IRuleBuilder<T, string> ruleBuilder)
        {
            return ruleBuilder.SetValidator(new RegularExpressionValidator(@"((?:[0-9]\-?){6,14}[0-9]$)|((?:[0-9]\x20?){6,14}[0-9]$)"));
        }
    }
    

    Regex接受6到14位的电话号码。

    这里,我要检查注册请求的验证。所以,我做了如下事情:

    public class RegisterDtoValidator : AbstractValidator<RegisterDto>
    {
        public RegisterDtoValidator()
        {
            RuleFor(x => x).SetValidator(new UserBaseDtoValidator());
        }       
    }
    

    所有其他验证工作正常。然而,regex是为下限工作的,但是当我超过14位时,验证不会被触发。

    使用相同的表达式 RegularExpressionAttribute

    1 回复  |  直到 7 年前
        1
  •  0
  •   Mark Shevchenko    7 年前

    (?:[0-9]\-?){6,14}[0-9]$ 表示6-14位数字加上字符串末尾的一位数字。

    只需添加 ^ 在图案开始处签名。 ^(?:[0-9]\-?){6,14}[0-9]$ 意思是6-14个数字加上整个字符串中的一个数字。

    $ 与字符串结尾匹配, [0-9]$ 与任何以数字结尾的字符串匹配。 ^ 与字符串开头匹配,因此 ^[0-9] 指任何以数字开头的字符串。 ^[0-9$ 与任何正好包含一个数字的字符串匹配。

    您的完整模式应该是:

    @"^((?:[0-9]\-?){6,14}[0-9])|((?:[0-9]\x20?){6,14}[0-9])$"