I’m trying to create a regex to allow alphanumeric strings with hyphens, underscores and spaces allowed. The string must start with a number or a letter and be a maximum total of 20.
Here is my code:
var regex = /^[a-zA-Z0-9]+([a-zA-Z0-9_ -]){0,20}$/;
var newName = "12345678901234567890233_pm";
if (regex.test(newName)) {
console.log('yes');
}else{
console.log('no');
}
My code always returns yes. Is my regex wrong please?
Thanks.
>Solution :
Your use of the + quantifier in the first character class does not do what you seem to think it does – it’s actually not at all necessary in this context. Additionally, since the first character class accounts for 1 of the 20 maximum characters, reduce the maximum quantifier in the second character class to 19:
var regex = /^[a-zA-Z0-9][a-zA-Z0-9_ -]{0,19}$/;
var newName = "12345678901234567890233_pm";
if (regex.test(newName)) {
console.log('yes');
}else{
console.log('no');
}