[英]Regex validation with fluent validation ASP.NET Core WebApi
I'm working with WebApi project and have used fluent validation for validating the request.我正在使用 WebApi 项目并使用流畅的验证来验证请求。
Userbase Dto.用户群 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.用户注册 Dto。
public class RegisterDto : UserBaseDto
{
}
UserBaseDtoValidator. 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
is a custom validator 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 is accepting 6 to 14 digit phone number. Regex 接受 6 到 14 位数字的电话号码。
Here, I want to check validation for registration request.在这里,我想检查注册请求的验证。 So, I have done something like:
所以,我做了类似的事情:
public class RegisterDtoValidator : AbstractValidator<RegisterDto>
{
public RegisterDtoValidator()
{
RuleFor(x => x).SetValidator(new UserBaseDtoValidator());
}
}
All other validations working fine.所有其他验证工作正常。 However, regex is working for lower limit but when I pass more than 14 digit, validation not getting triggered.
但是,正则表达式适用于下限,但是当我通过超过 14 位数字时,不会触发验证。
Same expression working with RegularExpressionAttribute
使用
RegularExpressionAttribute
相同表达式
(?:[0-9]\\-?){6,14}[0-9]$
means 6–14 digits plus one digit at the end of the string. (?:[0-9]\\-?){6,14}[0-9]$
表示 6-14 位数字加上字符串末尾的一位数字。
Just add the ^
sign at the start of pattern.只需在模式开头添加
^
符号即可。 ^(?:[0-9]\\-?){6,14}[0-9]$
means exactly 6–14 digits plus one digit in the entire string. ^(?:[0-9]\\-?){6,14}[0-9]$
表示整个字符串中正好是 6-14 位数字加上一位。
While $
matches with the end of string, [0-9]$
matches with any string that ends with a digit. $
匹配字符串的结尾, [0-9]$
匹配任何以数字结尾的字符串。 ^
matches with the start of string, so ^[0-9]
means any string that starts with a digit. ^
与字符串的开头匹配,因此^[0-9]
表示任何以数字开头的字符串。 ^[0-9$
matches with any string that contains exactly one digit. ^[0-9$
匹配任何只包含一位数字的字符串。
Your full pattern should look like:您的完整模式应如下所示:
@"^((?:[0-9]\-?){6,14}[0-9])|((?:[0-9]\x20?){6,14}[0-9])$"
尝试使用以下模式:
(^(?:[0-9]\-?){5,13}[0-9]$)|(^(?:[0-9]\x20?){5,13}[0-9]$)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.