I'm building a browser-based app which allows users to create folders with some .json files (not big deal). The thing is, the framework that I'm using (NW.js) doesn't appears to care about allowing users to create folders named "CON" or "NUL"; These are not supposed to be created, the files inside just vanish and it's somewhat difficult to delete the folder themselves.
I can no problem make something like this to prevent to happen:
var newFolder = "nul";
function checkFolderName(text) {
switch(newFolder) {
case "con":
console.log("folder can't be created")
break;
case "nul":
console.log("folder can't be created")
break;
// and so on... there's about 23 windows-reserved names that I could find
default:
console.log("folder can be created")
}}
checkFolderName(newFolder);
But I wonder if there is some easier way to check this through Regex/Javascript, or maybe some different approach to this idea.
Here's a little cleaner way to write what you want.
Function renamed to imply that it takes a string and returns a boolean.
If the input string is invalid, returns false.
All banned names are grouped together in an easily updated list.
Validity is checked by if the list contains the name.
function folderNameIsValid (name) {
let valid = false;
if (!name || typeof(name) !== 'string') {
return valid;
}
const bannedNames = [
'con',
'nul'
];
if (!bannedNames.includes(name.toLowerCase())) {
valid = true;
}
return valid;
}
if (folderNameIsValid('NUL')) {
console.log('folder can be created');
} else {
console.log('folder cannot be created');
}
If you want to use regex you can do it like this:
if (/^con|nul|abc|xyz$/.test(newFolder))
console.log("folder can't be created");
The | character means 'or'. so the test function will return true if newFolder is "con" or "nul" or "abc" or "xyz"
The ^ and the $ sign are the beginning and the ending of the string.
If you want to know exactly what was the illegal part, you can use this:
var matching = newFolder.match(/^con|nul|abc|xyz$/);
if (matching) {
console.log("folder can't be created, found " + matching[0]);
}
You can also use this notation of switch case:
switch (newFolder)
{
case "con":
case "nul":
case "abc":
case "xyz":
console.log("folder can't be created");
break;
default:
console.log("folder can be created");
}
My friend could help me to do this with regex:
let valid = /^(con|prn|aux|nul|com|lpt)\d*$/gi.test(newFolder)
console.log(valid) // true or false
However, it's starts to get pretty clanky if you want to add more "banned names", so jaredcheeda's suggestion it's pretty handy in this case