ASP.NET Core Web API:修复Fluent Validation手机号验证正则错误并实现指定格式
解决Fluent Validation手机号验证的正则错误及格式需求
问题分析
报错Invalid pattern '^\([0-9]{3})?\)$' at offset 12. Too many )'s.是因为正则表达式括号不匹配:\(是转义的左括号,但后续的)未转义,导致正则解析时判定右括号数量异常。同时需实现以234开头、总长度13位的纯数字手机号验证(对应提示消息234xxxxxxxxxxx的格式要求)。
修正方案
1. 修复正则表达式并匹配需求
调整后的正则需满足:
- 强制以
234开头 - 后续跟随10位数字,总长度固定为13位
- 仅允许纯数字格式
2. 调整验证规则顺序
先验证非空规则,再执行格式验证,避免空值触发格式校验错误。
最终代码
修正后的PhoneNumber扩展方法
public static IRuleBuilder<T, string> PhoneNumber<T>(this IRuleBuilder<T, string> ruleBuilder) { var options = ruleBuilder .Matches(@"^234\d{10}$") .WithMessage("Mobile number format should be 234xxxxxxxxxxx (13 digits total starting with 234)"); return options; }
调整后的AdminCreateDtoValidator
public class AdminCreateDtoValidator : AbstractValidator<AdminCreateDto> { public AdminCreateDtoValidator() { RuleFor(user => user.MobileNumber) .NotNull().WithMessage("Mobile Number cannot be null") .NotEmpty().WithMessage("Mobile Number field is required. ERROR!") .PhoneNumber(); } }
可选扩展:支持带符号的格式
如果需要兼容带括号或空格的格式(如(234) 1234567890),可将正则替换为:
.Matches(@"^\(?234\)?\s?\d{10}$") .WithMessage("Mobile number must start with 234, total 13 digits (optional parentheses or spaces allowed)");
内容的提问来源于stack exchange,提问作者Ayobamilaye
相关产品推荐
相关产品推荐

