I have the a vehicle registration number being validated by Joi in Node.js and need it to reject any string that contains whitespace (space, tab, etc.)
I tried the following schema, but Joi does let it go through:
const schema = {
regNo: Joi.string()
.regex(/^.*\S*.*$/)
.required()
.trim()
}
So, if I submit "JOI 777" the string is considered valid.
What am I doing wrong? Thanks in advance,
This part of your regex -> /^.*
is saying match anything, so the rest of your regEx is pretty much short circuited.
So your RegEx is a bit simpler, /^\S+$/
This is then saying, from the start to the end, everything has to be a None whitespace.. Also seen as this checks everything for whitespace, you could also take out your .trim()
..
eg.
const tests = [
"JOI 777", //space in the middle
"JOI777", //looks good to me
" JOI777", //space at start
"JOI777 ", //space at end
"JO\tI77", //tab
"ABC123", //another one that seems ok.
"XYZ\n111" //newline
];
tests.forEach(t => {
console.log(`${!!t.match(/^\S+$/)} "${t}"`);
});