首页 新闻 会员 周边

web api遇到RegularExpression特性的一个无比诡异的bug

0
悬赏园豆:100 [待解决问题]
   [RegularExpression(@"^[_a-zA-Z0-9]{6.24}?$", ErrorMessage = "{0}只能包含字母/数字/下划线")]

    public string Pwd { get; set; }


string pwd = "123456aa";
           Regex regex2 = new Regex("^[_a-zA-Z0-9]{6,24}$");
           Match match = regex2.Match(pwd);
           Console.WriteLine(match.Success && match.Index == 0);
           Console.WriteLine(match.Length == pwd.Length);

 

用web api的时候,上面那个pwd为123456aa的时候,一直通过不了验证.但是我把他的IsValid方法拿出来时,发现结果都为true.

最终我把问题定位为SetupRegex 的问题.

    public override bool IsValid(object value)
    {
      this.SetupRegex();
      string input = Convert.ToString(value, (IFormatProvider) CultureInfo.CurrentCulture);
      if (string.IsNullOrEmpty(input))
        return true;
      Match match = this.Regex.Match(input);
      if (match.Success && match.Index == 0)
        return match.Length == input.Length;
      return false;
    }


我自定义了一个近似于RegularExpression的自定义特性,其中SetupRegex方法如下

        private void SetupRegex()
        {
            if (this.Regex != null)
                return;
this.Regex = new Regex("^[_a-zA-Z0-9]{6,24}?$");
        }

奇异的事情发生了,通过了验证.........

另外一个地方就是.web api的Validate()方法不会调用实现了 IValidatableObject的类的

Validate方法. 


        
Cherbim的主页 Cherbim | 菜鸟二级 | 园豆:323
提问于:2015-07-11 10:56
< >
分享
所有回答(3)
0

我看到[RegularExpression(@"^[_a-zA-Z0-9]{6.24}?$", ErrorMessage = "{0}只能包含字母/数字/下划线")],别的还没看懂,不知道奇异的事跟这个有没有关系。

liqipeng | 园豆:1160 (小虾三级) | 2015-07-11 15:23
0

难道不是手误的将{6,24} 写成了{6.24}

幻天芒 | 园豆:37175 (高人七级) | 2015-07-11 15:57

对,那第二个问题呢......

支持(0) 反对(0) Cherbim | 园豆:323 (菜鸟二级) | 2015-07-16 13:34

@Cherbim: 为什么你实现了,它就要调用?难道不应该先注册吗?要不然它怎么知道你实现了呢~

支持(0) 反对(0) 幻天芒 | 园豆:37175 (高人七级) | 2015-07-16 14:04

@幻天芒: 如果是MVC的话,默认的模型绑定会走实现了IValidatableObject的action 参数类里的验证方法的.WEB API不知道咋做

支持(0) 反对(0) Cherbim | 园豆:323 (菜鸟二级) | 2015-07-18 09:55

@Cherbim: http://www.asp.net/web-api/overview/formats-and-model-binding/model-validation-in-aspnet-web-api  注意看最后。。。

支持(0) 反对(0) 幻天芒 | 园豆:37175 (高人七级) | 2015-07-18 10:58
0

唉,手误发现了惊天BUG,这正则表达式

稳稳的河 | 园豆:4216 (老鸟四级) | 2015-07-13 17:41
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册