I'm building a File manager with jQuery. Users can create folders and upload files. I need a Regual Expression (javascript) to check if the entered folder-name or the uploaded file-name is web-save. (no special chars or spaces are allowed)
The name should only contain alphanumeric values (a-z,A-Z,0-9), underscores (_) and dashes(-)
I'm building a File manager with jQuery. Users can create folders and upload files. I need a Regual Expression (javascript) to check if the entered folder-name or the uploaded file-name is web-save. (no special chars or spaces are allowed)
The name should only contain alphanumeric values (a-z,A-Z,0-9), underscores (_) and dashes(-)
Share Improve this question asked Oct 7, 2010 at 11:48 YensYens 9254 gold badges12 silver badges24 bronze badges 3 |4 Answers
Reset to default 12Don't bother your visitor, do it for him :)
var cleanName = function(name) {
name = name.replace(/\s+/gi, '-'); // Replace white space with dash
return name.replace(/[^a-zA-Z0-9\-]/gi, ''); // Strip any special charactere
};
cleanName('C\'est être');
This seems quite straightforward:
/^[\w.-]+$/
Useful tutorial
This is a regex to sanitize Windows files/folders. It will work for POSIX (linux, mac) too, since it's less restrictive.
function sanitizePath (path) {
return path.replace(/[\\/:*?"<>|]/g, '')
}
console.log(sanitizePath('\\x/:a*b?<>|y'))
function clean(filename) {
filename= filename.split(/[^a-zA-Z0-9\-\_\.]/gi).join('_');
return filename;
};
filename=clean("Vis'it M'ic ro_pole!.pdf");
[regex] +filename +validate
– splash Commented Oct 7, 2010 at 11:52