【问题标题】:Regex validation with fluent validation ASP.NET Core WebApi使用流畅验证 ASP.NET Core WebApi 进行正则表达式验证
【发布时间】:2019-02-07 10:25:26
【问题描述】:

我正在使用 WebApi 项目并使用流利的验证来验证请求。

用户群 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; }
}

UserRegister Dto.

public class RegisterDto : UserBaseDto
{
}

UserBaseDtoValidator.

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());
    }       
}

所有其他验证工作正常。但是,正则表达式适用于下限,但是当我通过超过 14 位时,验证不会被触发。

使用RegularExpressionAttribute 的相同表达式

【问题讨论】:

    标签: c# regex asp.net-core asp.net-core-webapi fluentvalidation


    【解决方案1】:

    (?:[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])$"
    

    【讨论】:

    • @HinaKhuman 如我所见,您的正则表达式检测到 7-15 位数字。如果您正好需要 6-14 位数字,只需删除两个表达式末尾的 [0-9] 即可。或将6,14 更改为5,13
    • 不,不工作。也许,流畅的验证有问题!
    【解决方案2】:

    尝试以下模式:

    (^(?:[0-9]\-?){5,13}[0-9]$)|(^(?:[0-9]\x20?){5,13}[0-9]$)
    

    【讨论】:

    • 这个答案可以/应该改进。请对其进行编辑并添加有关它如何解决问题的说明,以便原始发帖人和其他人了解问题所在。
    猜你喜欢
    • 2017-11-22
    • 1970-01-01
    • 1970-01-01
    • 2020-02-18
    • 1970-01-01
    • 2014-12-25
    • 2014-04-21
    • 2020-12-03
    相关资源
    最近更新 更多