[英]node typescript : regex to allow whitespace with at least one alphanum caracter with joi validation
I am using joi and regex to validate user input, I would like to accept only alpha num caracters where whitespace can be allowed.我正在使用 joi 和 regex 来验证用户输入,我只想接受可以允许空格的字母数字字符。 I've done the following :
我做了以下事情:
const schema = Joi.object({
value: Joi.string()
.regex(
/^[a-zA-Z0-9 ]*$/,
'message',
)
.max(100)
.required()
...
The problem is that now I allow user to fill a full string composed only of whitespaces, and that's not what I want, I accept whitespaces, only if they are between alphanum caracters.问题是现在我允许用户填充仅由空格组成的完整字符串,这不是我想要的,我接受空格,只有当它们在字母字符之间时。 I am using this to test : https://www.regextester.com/104025
我用它来测试: https : //www.regextester.com/104025
Try this one:试试这个:
/^[a-zA-Z0-9]+[a-zA-Z0-9 ]*[a-zA-Z0-9]+$/
I dont know if this is the easiest or most elegant way but [a-zA-Z0-9]+
matches one or more of [a-zA-Z0-9]
using the +
我不知道这是最简单的还是最优雅的方式,但
[a-zA-Z0-9]+
匹配一个或多个的[a-zA-Z0-9]
使用+
I added this to the front and end of your regex.我将此添加到正则表达式的前端和末尾。
Test and explanation: https://regex101.com/r/79uEWb/2/测试与说明: https : //regex101.com/r/79uEWb/2/
Specify at the beginning that space is not allowed [^ ]
在开头指定不允许使用空格
[^ ]
const withSpaceInFront = " hello"; const text = "hello there" const textAndNumbers = "hello 5" const textWithSpecialChars = "hello#" const numeric = 123 const textWithSpecialCharsAllowed = "general Kenobi..?" const regexNoSpace = /^[^ ][a-zA-Z0-9 ]*$/; console.log("no space in front") console.log(regexNoSpace.test(withSpaceInFront)); console.log(regexNoSpace.test(text)); console.log(regexNoSpace.test(textAndNumbers)); console.log(regexNoSpace.test(textWithSpecialChars)); console.log(regexNoSpace.test(numeric)); //if you want to accept special chars like ? or . just add them in your list of accepted chars const regexAllowedSpecialChars = /^[^ ][a-zA-Z0-9 ?.]*$/; console.log("no space in front & specific chars allowed") console.log(regexAllowedSpecialChars.test(textWithSpecialCharsAllowed));
Regex tests: https://regex101.com/r/8Ulpu9/1/正则表达式测试: https : //regex101.com/r/8Ulpu9/1/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.