简体   繁体   English

ASP.NET MVC数据注释正则表达式

[英]ASP.NET MVC Data Annotation Regular Expression

I'm having trouble to get a regex to work 我无法让正则表达式正常工作

    [Required]
    [Display(Name = "Challonge URL")]
    [RegularExpression(@"http://challonge.com/[a-zA-Z0-9]{1-20}", ErrorMessage = "Invalid challonge URL")]
    public string Challonge_URL { get; set; }

The input http://challonge.com/56h9ezkf is not valid when it should be, is there something wrong with the regular expression? 输入http://challonge.com/56h9ezkf应该是无效的,正则表达式有问题吗?

Yes, there are several things... 是的,有几件事...

  • you need to escape / and . 你需要逃脱/. using \\ because slash and dot mean things in regex and you want to match them literally 使用\\因为斜杠和点表示正则表达式中的内容,并且您想按字面意义匹配它们
  • it's {1,20} , not {1-20} {1,20} ,而不是{1-20}
  • you should probably add ^ at the beginning and $ at the end so it matches the entire string; 您可能应该在开头添加^ ,在末尾添加$ ,以使其与整个字符串匹配; otherwise garbage at the beginning or end of the URL will be considered valid 否则,URL开头或末尾的垃圾将被视为有效

^http:\\/\\/challonge\\.com\\/[a-zA-Z0-9]{1,20}$

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM