为什么不't这个正则表达式有效,并且在测试代码上运行良好

Why doesn't this regex work Even though it is valid and runs fine on test code

本文关键字:测试 代码 运行 有效 正则表达式 为什么不      更新时间:2023-09-26

我已经在SO上发布了几篇与此相关的帖子,但这是另一篇适用于测试代码的帖子,而不使用启用了clientScript的正则表达式验证器控件我希望上传时在客户端验证fileUpload。

<asp:RegularExpressionValidator id="rgvFile" runat="server" font-bold="true" errormessage="Only pdf, txt, doc, docx, png, gif, jpeg, jpg, zip, rar files allowed"
cssclass="rgvfile" enableclientscript="true" display="Dynamic" controltovalidate="fileUpload"
validationexpression="(.pdf|.txt|.doc|.docx|.png|.gif|.jpeg|.jpg|.zip|.rar)$"
text="Only pdf, txt, doc, docx, png, gif, jpeg, jpg, zip, rar files allowed" tooltip="Only certain files allowed. Filename must be within 30 letters and cannot contains invalid characters"></asp:RegularExpressionValidator>

验证表达式所做的是检查有效的文件扩展名[忘记扩展名伪造,在这里更改文件扩展名并上传。]。我在上面的regExHero、regexBudy上测试了所有验证文件。我也测试了如下。

"domreference.pdf".match(/(.pdf|.txt|.doc|.docx|.png|.gif|.jpeg|.jpg|.zip|.rar)$/);

从而产生正确的CCD_ 1。但当在正则表达式验证器中使用时,它甚至不会验证正确的文件名。

首先,请注意您没有逃脱这些点:

'.(pdf|txt|doc|docx|png|gif|jpeg|jpg|zip|rar)$

这不起作用,因为微软编写的脚本不是跨浏览器的,他们从来没有想过。

function RegularExpressionValidatorEvaluateIsValid(val) {
    var value = ValidatorGetValue(val.controltovalidate);
    if (ValidatorTrim(value).length == 0)
        return true;
    var rx = new RegExp(val.validationexpression);
    var matches = rx.exec(value);
    return (matches != null && value == matches[0]);
}

其中"val=文件上传的值",每个浏览器的值不同。因此,即使找到了有效的匹配,最后一个返回语句也会返回false,因为在这种情况下,值永远不会等于匹配