DataAnnotaion在客户端失败(冻结)?

Ban*_*hee 5 regex asp.net asp.net-mvc data-annotations

我有ASP.NET MVC网页,我使用DataAnnotation来验证客户端的表单.其中一个视图类具有如下属性:

[StringLength(100, MinimumLength = 3, ErrorMessage = "Länken måste vara mellan 3 och 100 tecken lång")]
[Display(Name = "Länk")]
[RegularExpression(@"^(http(s)?://([\w-]+.)+[\w-]+(/[\w- ./?%&=])?)?$", ErrorMessage="Länkgen är inte giltlig")]
        public string Url { get; set; }
Run Code Online (Sandbox Code Playgroud)

在视图中,我将此代码用于属性:

@Html.LabelFor(c => c.Url, true)
@Html.TextBoxFor(c => c.Url, new { @class = "tb1", @Style = "width:400px;" })
@Html.ValidationMessageFor(model => model.Url)
Run Code Online (Sandbox Code Playgroud)

粘贴到这样的URL时:

http://95rockfm.com/best-voicemail-giving-play-by-play-of-car-accident/

网页将锁定,我无法在wepage上做任何事情.如果我将其粘贴到:

http://95rockfm.com/best-voicemail-giving-play-by-play-of-car-accident

它工作得很好.

这些javascript文件包含在网页的底部:

<script type="text/javascript" src="/Scripts/jquery.qtip.min.js"></script>
<script src="/Scripts/jquery-1.7.1.min.js"></script>
<script src="/Scripts/jquery-ui-1.8.20.min.js"></script>
<script src="/Scripts/jquery.validate.min.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.min.js"></script>
Run Code Online (Sandbox Code Playgroud)

完全相同的问题同时适用于IE和Chrome.然而,IE将回来并说一个脚本花了很长时间,一个按钮停止脚本.但是当切换输入控件时,脚本将再次运行并查看网页.

我没有使用任何自定义的东西,为什么我得到这个?

Mar*_*der 5

.在正则表达式中匹配任何字符(实际上,这段时间与URL中的域后面的斜杠相匹配).您需要将其转义或将其放入字符类中以匹配句点.像这样:

@"^(http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=])?)?$"
Run Code Online (Sandbox Code Playgroud)

或者:

@"^(http(s)?://([\w-]+[.])+[\w-]+(/[\w- ./?%&=])?)?$"
Run Code Online (Sandbox Code Playgroud)

如果您不这样做,并且模式找不到匹配项,则您将进行嵌套重复,并具有指数量的可能组合.由于nemesv在评论中将您联系起来,这会导致灾难性的回溯.但是,如果要匹配组内的文字句点,则整个组的每次重复都必须以句点结束,因此没有指数量的组合.

要查看"指数数量的组合"的含义,我只会链接到我的两个前答案(实际上是今天的一个):

还有一件事,为什么你的模式失败(灾难性的回溯主要是失败匹配的问题):在第一个斜线后只需要一个字符.您可能希望允许任意长的路径和查询字符串,因此添加+到该字符类:

@"^(http(s)?://([\w-]+[.])+[\w-]+(/[\w- ./?%&=]+)?)?$"
Run Code Online (Sandbox Code Playgroud)

但是,一般来说,为什么重新发明轮子而不是谷歌搜索已建立的URL正则表达式模式.