How can I create a regex for folder names in javascript?
I want to check the folder name, it should not start with a number or any special character, I'm not sure what special characters are allowed inside folder names, kindly help.
here is my function
function validateFileName() {
var re = /[^a-zA-Z0-9\-]/;
if(!re.test($('#new_folder_name').value)) {
alert("Error: Input contains invalid characters!");
$('#new_folder_name').focus();
return false;
}
// validation was successful
return true;
}
source to share
There is a function in C # that returns a list of invalid path characters . In addition, Naming Files, Paths, and Namespaces contains a list of reserved characters that cannot be used in both folder names and files. Here is a regular expression that covers all of these restrictions:
var RealInvalidPathChars = /[<>:"\/\\|?*\x00-\x1F]/;
You can check for any of the characters inside the string and that will be the wrong way.
In addition, there is a list of reserved words that cannot be used as folder names, and we can also use them in a regular expression:
/^(?:aux|con|clock\$|nul|prn|com[1-9]|lpt[1-9])$/i
If this regular check returns true, the path is invalid.
Here's a snippet that brings it all together:
$( "#new_folder_name" ).submit(function( event ) {
var rx = /[<>:"\/\\|?*\x00-\x1F]|^(?:aux|con|clock\$|nul|prn|com[1-9]|lpt[1-9])$/i;
if(rx.test($( "input:first" ).val())) {
alert("Error: Input contains invalid characters!");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="new_folder_name">
<input type="text" value="<INVALID>">
<input type="submit" value="Go">
</form>
source to share
According to File Naming, Path and Namespace on MSDN
The following special characters are retained:
< (less than)
> (greater than)
: (colon)
" (double quote)
/ (forward slash)
\ (backslash)
| (vertical bar or pipe)
? (question mark)
* (asterisk)
And the following keywords are also reserved
CON, PRN, AUX, NUL, COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9, LPT1, LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, and LPT9.
Which are insensitive to the case.
So, given these facts, a possible regex could be:
[^<>:"/\|?*(?:aux|con|nul|prn|com[1-9]|lpt[1-9])]
So your converted function will be
function validateFileName() {
var re = /[^<>:"/\|?*(?:aux|con|nul|prn|com[1-9]|lpt[1-9])]/;
if(!re.test($('#new_folder_name').value)) {
alert("Error: Input contains invalid characters!");
$('#new_folder_name').focus();
return false;
}
// validation was successful
return true;
}
source to share