Reputation:
I am getting very confused in writing the regex pattern for my requirement. I want that a text field should not accept any special character except underscore and hyphen. Also, it shouldn't accept underscore, hyphen, and space if entered alone in the text field.
I tried following pattern->
/[ !@#$%^&*()+\=\[\]{};':"\\|,.<>\/?]/;
but this is also allowing underscore and hyphen, as well as space if entered alone.
Upvotes: 1
Views: 69
Reputation: 8650
Rather than matching what you do not want, you should match what you actually want.
Since you never specified if you string could have letter, number and spaces in it, i just assumed it was a single word, so I matched uppercase and lowercase letters only, with underscore and hyphen.
^(([A-Za-z])+([\-|_ ])?)+$
I have created a regex101 if you wish to try more cases.
Upvotes: 1
Reputation: 2587
If you want your string not to contain special characters except underscore and hyphen. But there is an exception for that if they contain space with the hyphen and underscore, then you can handle that exception separately. This will make your code easier to understand and easily adaptable for further exceptions.
function validateString(str){
let reg = /[^!@#$%^&*()+\=\[\]{};':"\\|,.<>\/?]/g;
let match = str.match(reg);
console.log(match);
if(match && (match.includes(" ") || match.includes("_") || match.includes("-")) && (!match.join(",").match(/[a-zA-Z]/))){
// regex contains invalid characters
console.log(str + ": Invalid input");
}
else if(match){
console.log(str + ": Valid string");
}
}
let str = "-_ ";
let str1 = "Mathus-Mark";
let str2 = "Mathus Mark";
let str3 = "Mathus_Mark";
let str4 = " ";
let str5 = "-";
let str6 = "_";
validateString(str);
validateString(str1);
validateString(str2);
validateString(str3);
validateString(str4);
validateString(str5);
validateString(str6);
Upvotes: 0