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 need to have a set for each type, with or without trailing commas
https://regex101.com/r/z7kQrG/5
const re = /^(?:[A-Z0-9]{3}(?:, ?))*[A-Z0-9]{1,2}$|^(?:[A-Z0-9]{3}(?:, ?))*[A-Z0-9]{3}(?:, ?)?$/
const inputs = `B
BR
BRU
BRU,
BRU,
BRU, A
BRU, ALC
BRU, ALC,B
BRUU
BRU ALC
B,
BR,
B,
BR, `.split('\n');
//console.log(inputs);
inputs.forEach(input => console.log(input,':',re.test(input)));
pre { font-family: "Noto Sans Mono", monospace; }