javascript正则表达式评估导致浏览器挂起 [英] javascript regex evaluation causes browser to hang

查看:71
本文介绍了javascript正则表达式评估导致浏览器挂起的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在用于自定义验证时,Regex出现了问题.

I have a problem with Regex when used for custom validation.

我有这种不引人注目的方法:

I have this unobtrusive method:

jQuery.validator.addMethod("isRegex", function (value, element, params) {
    if (value.length < 1) return true;
    var re = new RegExp(params.regex);
    var match = re.exec(value);
    return match;
});

起初,我使用此正则表达式来验证电子邮件表单字段:

At first I was using this regular expression for validation an email form field:

^\w+([-+.]*[\w-]+)*@(\w+([-.]?\w+)){1,}\.\w{2,4}$

该事件将被触发"onkeyup",起初它将起作用,但是如果电子邮件地址太长,则将导致浏览器挂起,并且恢复的唯一方法是重新启动浏览器.这是在IE和chrome上发生的,但也可能在Firefox上发生.

The event would be fired "onkeyup" and at first it would work but if the email address was too long it would cause the browser to hang and the only way to recover would be restarting the browser. This happened on IE and chrome but probably Firefox too.

因此,例如键入"test@test.com"将可以正常工作. "testtesttest@ttest.com"也可以毫无问题地工作,但是"testtesttesttesttesttesttesttest@ttest.com"将挂在最后一个字母上.

So for example typing "test@test.com" would work fine. "testtesttest@ttest.com" would also work without problems but "testtesttesttesttesttest@ttest.com" would hang towards the last letters.

起初我以为正则表达式可能是一个无效的正则表达式,会导致无限循环或锁定,所以我将其更改为简单的东西:

At first I thought maybe the regex was an inneficient one causing infinite loops or locks so I changed it to something simple:

^.+@.+\..+$

部分成功,我可以输入更长的电子邮件地址,但最终仍会挂起.

Partial success, I can type longer email addresses but it still hangs eventually.

然后我想我应该禁用onkeyup事件,也许只是在模糊时验证并为此使用:

Then I thought I should disable the onkeyup event and maybe just validate on blur and for that I used:

   $("#divEmail input[data-val-fieldregex]").keyup(function () { return false; });

现在禁用了键盘输入,但是浏览器由于模糊而挂起,因此表示代码:

Now the keyup is disabled but the browser hangs on blur, so it means the code:

    var re = new RegExp(params.regex);
    var match = re.exec(value);

必须无法处理较大的值.

Must be unable to handle large values.

有什么想法吗?

推荐答案

尝试将([-+.]*[\w-]+)*替换为([-.]\w+)*

^\w+([-.]\w+)*@\w+([-.]\w+)*\.\w{2,4}$

您可以在此处找到有关灾难性回溯的更多信息.

You can find more informations about catastrophic backtracking here.

第二种模式也可能导致灾难性的回溯,因为点可以与文字点和arobase相匹配.

The second pattern can cause a catastrophic backtracking too since the dot can match the literal dot, and the arobase.

请注意,这种模式非常基础,并且会排除许多格式正确的电子邮件地址.

Note that this kind of pattern is very basic and will exclude many well formed email addresses.

这篇关于javascript正则表达式评估导致浏览器挂起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆