Neil2526
asked on
Javascript Regex filename validation
I am trying to weed out 'bad' characters when a user is creating a filename. I am doing so with Javascript. Below is my code, another set of eyes would be great.
I am always getting my else condition "This is an invalid..."
Thanks.
I am always getting my else condition "This is an invalid..."
Thanks.
<form enctype='multipart/form-data' action='web_query2.php' method=POST name='web_query' onsubmit=\"return blah(document.getElementById('txt').value);\">
function blah(str) {
if (/^[^\\\/\:\*\?\"\<\>\|\.]+(\.[^\\\/\:\*\?\"\<\>\|\.]+)+$/.test(str)) {
alert(\"valid file name\");
return true;
}
else {
alert(\"This is an invalid filename, please try again!\");
return false;
}
}
Do you have a particular reason for not allowing multiple extensions? "archive.tar.gz" is an example of one.
ASKER
Of course. The user is creating a csv data file.
so why not also check for .csv ?
ASKER
they are not creating the extension, only the filename.
ie:
<th align=\"center\" class=\"fields\">
<input type=\"text\" id=\"txt\" name=\"filename\">.csv
</th>
ie:
<th align=\"center\" class=\"fields\">
<input type=\"text\" id=\"txt\" name=\"filename\">.csv
</th>
ASKER
human -
I tried your snipit, too and it works fine. I am still not hitting my first condition. I am always hitting my else clause. Attached is the full php file.
file.txt
I tried your snipit, too and it works fine. I am still not hitting my first condition. I am always hitting my else clause. Attached is the full php file.
file.txt
Oww ok, so the input is only the file name without extension ?
ASKER
yes. i think it has something to do with my regex.
But I used the same regex that you have used.
ASKER
the regex checks for:
XXX.XXX
My form submits:
XXX
ie:
<th align=\"center\" class=\"fields\">
<input type=\"text\" id=\"txt\" name=\"filename\">.csv
</th>
The user does not put in the DOT and the file extension.
XXX.XXX
My form submits:
XXX
ie:
<th align=\"center\" class=\"fields\">
<input type=\"text\" id=\"txt\" name=\"filename\">.csv
</th>
The user does not put in the DOT and the file extension.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Open in new window