【问题标题】:.NET ComponentModel.DataAnnotations issue with RegularExpression attribute.NET ComponentModel.DataAnnotations 问题与 RegularExpression 属性
【发布时间】:2011-10-12 16:05:13
【问题描述】:

我必须验证一个应该包含小时数的字符串(例如 00 到 23)。

因此我设置了如下注释:

 [RegularExpression("[01]?[0-9]|2[0-3]", ErrorMessage = "Error")]
 public string JobStartHour {...}

不幸的是,这个正则表达式与从 20 到 23 的输入不匹配,因为它应该这样做(恕我直言)。

这个 RegularExpression 属性不使用普通的旧 Regex.IsMatch 吗?

Regex.IsMatch("22", "[01]?[0-9]|2[0-3]")

返回真...

编辑:我知道,使用字符串来存储数字并不是最好的主意,但是,这个正则表达式问题很烦人。

【问题讨论】:

  • 我已经更新了我的答案,使其适用于“0”或“00”。希望这能解决您的问题。

标签: regex asp.net-mvc-3 validation


【解决方案1】:

这种模式会起作用。我遇到了same thing。它与使用括号正确建立分组有关。如果 RegExAttribute 无法弄清楚,它似乎只是在管道符号处退出。

这是一个单元测试。

    [TestMethod]
    public void CheckHours()
    {
      var pattern = "([0-1][0-9])|(2[0-3])|([0-9])";
      int cnt = 0;

      var hours = new string[]
        { "1","2","3","4","5","6","7","8","9",
          "01","02","03","04","05","06","07","08","09",
          "10","11","12","13","14","15","16","17","18","19",
          "20","21","22","23" };

      var attribute = new RegularExpressionAttribute(pattern);
      bool isMatchOk = false;
      bool isAttrOk = false;

      foreach (var hour in hours)
      {
        isMatchOk = System.Text.RegularExpressions.Regex.IsMatch(hour, pattern);
        isAttrOk = attribute.IsValid(hour);

        if (isMatchOk & isAttrOk)
        { cnt += 1; }
        else
        { Debug.WriteLine(hour + " / " 
          + isMatchOk.ToString() + " / "
          + isAttrOk.ToString()); }
      }

      Assert.AreEqual(32, cnt);
    }

【讨论】:

    【解决方案2】:

    试试这个:

    [RegularExpression("2[0-3]|[01]?[0-9]", ErrorMessage = "Error")]
     public string JobStartHour {...}
    

    【讨论】:

      【解决方案3】:

      不知道为什么这个正则表达式没有被正确解释,但是一个解决方案是实现一个CustomValidation,这很方便。

         [CustomValidation(typeof(MyCustomValidation), "Validate24Hour")]
           public string JobStartHour {...}
      
      ...
      
        public class MyCustomValidation
          {
              public static ValidationResult Validate24Hour(string candidate)
              {
                  bool isValid = false;
               ...
                  if (isValid)
                  {
                      return ValidationResult.Success;
                  }
                  else
                  {
                      return new ValidationResult("Error");
                  }
              }
         }
      

      【讨论】:

        【解决方案4】:

        您必须将| 分组才能正常工作。

        我成功尝试了,这应该正是您的正则表达式,但分组并限于开始和结束:

        ^([01]?[0-9]|2[0-3])$
        

        您命名的 Regex.IsMatch 行在我机器上的每个表达式上都返回 true。

        【讨论】:

          猜你喜欢
          • 2013-05-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-29
          • 1970-01-01
          • 2012-02-09
          相关资源
          最近更新 更多