如果字符串包含“”(空格),如何使 Joi regex() 验证失败?

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

我在 Node.js 中有一个由 Joi 验证的车辆登记号,需要它拒绝任何包含白色的字符串space(space、制表符等)

我尝试了以下架构,但 Joi 确实让它通过了:

  const schema = { 
    regNo: Joi.string()
     .regex(/^.*\S*.*$/)
     .required()
     .trim()
    }

因此,如果我提交 "JOI 777",则该字符串被视为有效。

我做错了什么? 提前致谢,

要从字符串中跳过白色space,只需使用:

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

如果你有不止一个 space 使用这个 :

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

有关详细信息,请参阅下面的 link: Remove whitespaces inside a string in javascript

你的正则表达式的这一部分 -> /^.* 说匹配任何东西,所以你的正则表达式的其余部分几乎是短路的。

所以你的 RegEx 有点简单,/^\S+$/

这就是说,从头到尾,所有内容都必须是 None 空格。这也被视为检查所有内容是否有空格,您也可以取出 .trim() ..

例如

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

怎么样

export const authenticateValidation = Joi.object({
    last_name: Joi.string()
      .alphanum()
      .min(1)
      .required(),
})