开发者

Regular expression in data annotation not working

开发者 https://www.devze.com 2023-02-28 00:15 出处:网络
I have this data annotation in my class [Required(ErrorMessage = \"Introduce a number!\")] [RegularExpression(\"[0-9]+\", ErrorMessage = \"Only numbers allowed\")]

I have this data annotation in my class

 [Required(ErrorMessage = "Introduce a number!")]
 [RegularExpression("[0-9]+", ErrorMessage = "Only numbers allowed")]
   public int number { get; set; }

The firs开发者_JS百科t data annotation works great but the second one doesn't work, if I introduce a letter or something that is not a number, it shows me the default message...any ideas?

It shows the value 'foo' is not valid for number


Give this a try: [RegularExpression(@"^\d+$", ErrorMessage = "Only numbers allowed")]


by any change are you using jquery 1.5? iirc the unobtrusive validation is broken for that version if you are using the unobtrusive validation that comes with a new mvc project. IIRC I use the same expression as the poster about and it works for me.


First it try to convert to int since the datatype is int and therefore u see default message. If u use datatype string then ur regex will work.

0

精彩评论

暂无评论...
验证码 换一张
取 消