简体   繁体   中英

How to make Joi regex() validation fail if the string contains “ ” (whitespace)?

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}"`); }); 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM