Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create regular expression for folder names in javascript?

i want to validate a folder name , it should not start with a number , or any special character, i am not sure about what special symbols 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;
      }
like image 541
Anky Avatar asked Mar 16 '23 03:03

Anky


2 Answers

As per the Naming Files, path and Namespaces article by MSDN

The following special characters are reserved:

< (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 case incensitive.

So considering those facts, the possible regex can be:

[^<>:"/\|?*(?:aux|con|nul|prn|com[1-9]|lpt[1-9])]

So your transformed 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;
      }
like image 54
mohamedrias Avatar answered Apr 25 '23 14:04

mohamedrias


Just check for the folder name starts with a letter and does not start with . (Dot)

var re = /^[a-zA-Z].*/;
re.test(folder_name);

This would return true only if the folder name starts with a letter.

like image 42
Avinash Raj Avatar answered Apr 25 '23 14:04

Avinash Raj