开发者

Detect some reserved characters in a string with Javascript

I have a file input in a form that uploads an MP3 file, but I´d like to detect reserved characters to my system in the filename, like ! @ or any other.

All codes I´ve found replace these characters, but I just want to detect them to alert the user. I think it will be easy with regular expressions, but I dont know about them.

I´m using JQuery/Javascript.

Edit to improve my problem description:

I´m working in a CodeIgniter application that allows user to upload MP3 files to the server. I use jQuery to manage client side forms. The CI upload class converts spaces in the file name to underscores and everything works. But in testing the application I uploaded an MP3 file with a (!) in the name, and I got troubles with it.

I just want to insert a javascript conditional before the file is uploaded to evaluate if the开发者_StackOverflow中文版 user´s filename contains a (!) (or any other I´d like to add later) to ask for the file to be renamed if it does.


Consider not blocking any characters at all. It's just a hassle for the user, and on exotic systems with strange path characters, you may end up not letting the user upload anything at all.

Let the user upload the file, and store the file name on the server in URI-Encoded form (in PHP, urlencode() would be the right function to go). This makes the file name compatible with your OS, and allows the user to keep any special characters in it when re-downloading the file.


One way to do this would be to compare the actual value of the input field to one encoded by encodeURIComponent. If they are the same, the filename is safe.

Be aware, though, that the browser may not report any filename at all. My plugin responds to this by returning true if no value is returned. This may, of course, mean that no value has been set.

jQuery plugin:

(function($) {
    $.fn.fileNameIsValid = function() {
        var val = this[0].value.replace('C:\\fakepath\\', '');

        return !val || encodeURIComponent(val) === val;
    }
}(jQuery));

You can then call this as so:

if ($('#yourFileInput').fileNameIsValid()) {
    // filename validates
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜