开发者

How do you write a Javascript Regex that matches if file extension is not within (exe|js|htaccess)

I'm trying to write a javascript regexp for a blacklist of file extensions. I'm using a jquery plugin that has an option for acceptable file types that takes a regex, but rather than maintain a whitelist we would like to maintain a blacklist. So I need the regex to only match if the string doesn't contain certain file extensions. Currently there is a regex we use to whitelist photo extensions on our photo upload:

/(\.|\/)(gif|jpe?g|png)$/i

For our document upload we would like to simply do a blacklist, but I haven't been able to make the ?! delimeter work. So for the sake of an example how would I reverse this regex to match as long as the file extension doesn't contain g开发者_StackOverflow中文版if, jpg, jpeg, png?

I've tried several different ways of using the ?!, but nothing I've tried has worked properly. Heres some examples of what I have tried unsuccessfully:

/(\.|\/)(?!gif|jpe?g|png)$/i

/(\.|\/)(?!(gif|jpe?g|png))$/i

Essentially I need this regex to always return true unless the blacklisted file extensions are matched.


This works:

/\.(?!(?:exe|js|htaccess)$)|\/(?!(?:exe|js|htaccess)$)/i

I think it's because the "match only if not followed by" doesn't like parentheses before it, but I'm not sure.

This new regex now works with the parentheses and multiple extensions:

/^.*(\.|\/)(?!(exe|js|htaccess)$)(?![^\.\/]*(\.|\/))/i

However, to allow files with no extension, this must be used:

/(^.*(\.|\/)(?!(exe|js|htaccess)$)(?![^\.\/]*(\.|\/)))|(^[^\.]+$)/i
//                                                     ^^^^^^^^^
//                                  This part matches a name without any dots

Looking at the complexity of that regex, I suggest that you implement something server-side or use another plugin.


Hack the jQuery plugin to accept a callback function instead of (or in addition to) a regular expression. Use the negation operator (!) and the positive regular expression to supply an appropriate callback. And write a mail to the maintainer of the plugin asking him to accept your patch.


I'm not a regex expert, but something like this appears to work: /\.(exe|js|htaccess)$/ig.test(filename) true results when the file is on your blacklist.

var shouldblockUpload = /\.(exe|js|htaccess)$/ig.test(filename);
//Inform user illegal upload

You can also explicitly only allow certain filetypes through the accept attribute on file inputs to help hint users to the right ones.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜