Reputation: 417
I am new at creating regulars expressions, but I am not sure how to do it to validate the creation of the name of a pdf file (created by myself). I don't want any special character or spaces, etc. I want to do it with Javascript, I don't know if that is important. Any help would be appreciated. Thank you.
Upvotes: 1
Views: 2763
Reputation: 1336
Assuming some common practices about file names, I would suggest one restricts a filename to alphanumeric-characters, slash, underscore and some brackets, then generally I would use the following piece of code
var patt =/^[a-z0-9_()\-\[\]]+\.pdf$/i;
var fileName = "my_test.pdf";
if (fileName.search(patt) < 0) {
// filename doesn't match the Regex
} else {
// filename matches the Regex
}
Generally the JS regex has two parts in this case, /regex/i where regex is the regex (doh), and i is a switch meaning "ignore-case". The regex itself says that anything from a-z, 0-9, underscore, parenthesis, (escaped) slash, (escaped) opening and closing square brackets, should be allowed at least one time (the + sign), and this should be followed by a (escaped) dot and the "pdf" string.
The ^ sign stands for "beginning of string" and the $ stands for "end of string". So this will help you avoid situation like this:
%`some_valid_name.pdf``*\
If you do not put the ^ and $ signs, this will be a valid match, according to regex.
Upvotes: 5