【问题标题】:How can I validate a property against a regular expresssion and still allow it to be null or empty?如何根据正则表达式验证属性并仍然允许它为空或为空?
【发布时间】:2009-06-30 21:31:20
【问题描述】:

我正在使用 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;}

【问题讨论】:

    标签: .net regex validation application-blocks


    【解决方案1】:

    您可以尝试将其添加到表达式的开头:

    ^$|
    

    它应该匹配空字符串或任何跟在 | 后面的正则表达式。 ...

    【讨论】:

      【解决方案2】:

      这只是一种预感(我目前无法测试,因为我无权访问验证应用程序块),但您可以尝试通过在开头和结尾)?

      [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; }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-03-19
        • 1970-01-01
        • 2015-05-24
        • 1970-01-01
        • 2012-10-09
        • 1970-01-01
        • 2018-12-11
        • 1970-01-01
        相关资源
        最近更新 更多