1

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,

  • Your first part of you regex is going to match anything,. I think what you want is a lot simpler, match any none-whitespace `/^\S+$/` , IOW: if a whitepace appears it should fail. – Keith Nov 20 '18 at 12:03

3 Answers3

2

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}"`);
});
Keith
  • 22,005
  • 2
  • 27
  • 44
0

for skipping whitespace from string just use:

"hello world".replace(/\s/g, "");

if you have more than One space use this :

"this string has more than one space".replace(/ /g, '');

for more detail see this link below: Remove whitespaces inside a string in javascript

Babak Abadkheir
  • 2,222
  • 1
  • 19
  • 46
  • 1
    `if you have more than One space use this`, your first one will remove multiple spaces too,.. Your second one will ONLY remove spaces, not tabs / newline etc. – Keith Nov 20 '18 at 12:21
  • tnx for the tips I realized now – Babak Abadkheir Nov 20 '18 at 12:25
  • This doesnt really answer the person's question. They are looking to have joi reject a value not modify incomming values. – unflores Nov 20 '18 at 13:30
  • Hi all, thanks for the answers. Yes, the answer provided by Keith worked as needed within Joi. Much appreciate everyone's attention! – Nikolay Chekan Nov 21 '18 at 09:27
  • This answer is rather irrelevant. He doesn't want to remove whitespaces instead he want to raise validation error. This is especially important for password fields. Maybe Joi should implement a method to disallow a special character in a string. – Capan Apr 01 '21 at 10:33
-1

How about

export const authenticateValidation = Joi.object({
    last_name: Joi.string()
      .alphanum()
      .min(1)
      .required(),
})
Daniel
  • 839
  • 10
  • 20