I would like to validate user input in an web application with a regex. The user is allowed to type three character words and separate them by a comma or comma followed by space.
Valid input could be: 'B' 'BR' 'BRU' 'BRU,' 'BRU, ' 'BRU, A' 'BRU, ALC' 'BRU, ALC,B' and so on.
Invalid input would be 'BRUU' or 'BRU ALC'
I wanted to solve this task with a Regex match, but I could not quite get it right. I ended up with this Regex:
/^(?:[A-Z0-9]{1,3}(?:, |,)?)*$/
which unfortunately allows input like "BRUALC"
I solved it with additional runtime check:
function isValid(input) {
const format = /^(?:[A-Z0-9]{1,3}(?:, |,)?)*$/;
if (!format.test(input)) return false;
// Split the words and validate each
const words = input
.split(/, ?/)
.filter(w => w.length > 0); // skip empty trailing entries
return words.every(w => /^[A-Z0-9]{1,3}$/.test(w));
}
but I wonder if there is a solution using only a regular expression
You can do it in a single regex by requiring a comma between words:
const isValid = (str: string) => /^[A-Z0-9]{3}(?:,\s?[A-Z0-9]{1,3})*(?:,\s?)?$/.test(str);
^
[A-Z0-9]{3}
(?:,\s?[A-Z0-9]{1,3})*
A non-capturing group repeated zero or more times:
,
— a required comma between words\s?
— optional space[A-Z0-9]{1,3}
— another 1 to 3 alphanumeric charactersThis handles subsequent words, like:
"BRU,ALC"
"BRU, 1"
"BRU,ABC,2B"
(?:,\s?)?
Allows an optional trailing comma, with optional space.
Matches strings like:
"BRU,ALC,"
"BRU,ALC, "
$
That should cover all your valid cases in one shot, with no extra runtime checks needed.