[英]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.) 我有一个由Joi在Node.js中验证的车辆登记号,需要它拒绝包含空格(空格,制表符等)的任何字符串。
I tried the following schema, but Joi does let it go through: 我尝试了以下模式,但Joi确实通过了:
const schema = {
regNo: Joi.string()
.regex(/^.*\S*.*$/)
.required()
.trim()
}
So, if I submit "JOI 777" the string is considered valid. 因此,如果我提交“ JOI 777”,则该字符串被视为有效。
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. regex的这一部分->
/^.*
表示匹配任何内容,因此regEx的其余部分几乎是短路的。
So your RegEx is a bit simpler, /^\\S+$/
所以您的RegEx有点简单,
/^\\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()
.. 这就是说,
.trim()
,所有内容都必须为None空格。也可以看到它检查所有空格,您也可以取出.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 有关更多详细信息,请参见下面的链接: 删除javascript中字符串内的空格
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.