RSS

Regular expression for checking special characters in a string or file name

30 Dec

Today I have faced a problem that codeigniter cannot upload a file if the filename name contain special character. I solved the problem by validatiing the file name with javascript.

Suppose you have a form file elament like this

<input type=”file” name=”baseFile” id=”base-file” />

Then i get the file name by jQuery:

var filename = $(‘#base-file’).val();

and check by a function :

if(!checkSpecialCharacter(filename)){
alert(‘The file name may have special character. Please rename the file name and try to upload again.’);
return false;
}

The function is :

// check file name has special character
function checkSpecialCharacter(filename){
var re = new RegExp(“^[^<>%$#%@|]*$”);
var specialchars = re.test(filename);
return specialchars;
}

Note : if the function return false then the special character exist in the file name. You can add more special character in[^ special_character].

Advertisements
 
Leave a comment

Posted by on December 30, 2011 in javascript, jQuery

 

Tags: , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: