如何根据正则表达式验证属性并仍然允许其为 null 或为空?
我正在使用 Microsoft 的验证应用程序块。 我有一个包含电话号码的字符串属性。 我有一个 RegexValidator,它可以很好地确保属性中只有电话号码类型字符串,但该属性还应该允许为 null 或空字符串的值。
目前,当值为 null 或空时,此验证器将失败。
我该如何解决这个问题?
(我知道这个正则表达式在这种格式下有点难以阅读,所以我提供了一个链接来测试它。)
// the regex below can be found and tested at: http://regexlib.com/RETester.aspx?regexp_id=536
[RegexValidator(@"^(?:(?<1>[(])?(?<AreaCode>[2-9]\d{2})(?(1)[)])(?(1)(?<2>[ ])|(?:(?<3>[-])|(?<4>[ ])))?)?(?<Prefix>[1-9]\d{2})(?(AreaCode)(?:(?(1)(?(2)[- ]|[-]?))|(?(3)[-])|(?(4)[- ]))|[- ]?)(?<Suffix>\d{4})$", MessageTemplateResourceName = "InvalidPhoneNumberMessage", MessageTemplateResourceType = typeof(Xltech.Common.Resources.XLStrings))]
public string NotificationCellNumber {get; set;}
I'm using the Validation Application Block from Microsoft. I have a string property which holds a phone number. I have a RegexValidator on it which works pretty well for ensuring only phone number type strings are in the property, but the property should also allow values that are null or an empty string.
Currently the this validator will fail when the value is null or empty.
How can I get around this?
(I know this regex is a tad difficult to read in this format so I supplied a link to test it at.)
// the regex below can be found and tested at: http://regexlib.com/RETester.aspx?regexp_id=536
[RegexValidator(@"^(?:(?<1>[(])?(?<AreaCode>[2-9]\d{2})(?(1)[)])(?(1)(?<2>[ ])|(?:(?<3>[-])|(?<4>[ ])))?)?(?<Prefix>[1-9]\d{2})(?(AreaCode)(?:(?(1)(?(2)[- ]|[-]?))|(?(3)[-])|(?(4)[- ]))|[- ]?)(?<Suffix>\d{4})$", MessageTemplateResourceName = "InvalidPhoneNumberMessage", MessageTemplateResourceType = typeof(Xltech.Common.Resources.XLStrings))]
public string NotificationCellNumber {get; set;}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以尝试将其添加到表达式的开头:
它应该与空字符串或 | 后面的任何正则表达式匹配 ...
You could try adding this to the beginning of the expression:
It should match the empty string or any regex that follows the | ...
这只是一种预感(我目前无法测试,因为我无权访问验证应用程序块),但您可以尝试通过用
(?: 开头,
)?
结尾:This is just a hunch (and I can't test at the moment because I don't have access to the Validation Application Block), but you could try making the entire regex optional by wrapping it with
(?:
at the beginning and)?
at the end: