问题描述
我正在使用joi和regex验证用户输入,我只接受允许空格的alpha num字符。我已完成以下操作:
const schema = Joi.object({
value: Joi.string()
.regex(
/^[a-zA-Z0-9 ]*$/,'message',)
.max(100)
.required()
...
问题是,现在我允许用户填充仅由空格组成的完整字符串,这不是我想要的,我接受空格,只有它们位于字母字符之间。我正在用它来测试:https://www.regextester.com/104025
解决方法
尝试这个:
/^[a-zA-Z0-9]+[a-zA-Z0-9 ]*[a-zA-Z0-9]+$/
我不知道这是最简单还是最优雅的方法,但是[a-zA-Z0-9]+
使用[a-zA-Z0-9]
+
中的一个或多个
我将此添加到了正则表达式的前端和后端。
测试与解释: https://regex101.com/r/79uEWb/2/
,请在开始时指定不允许使用空格[^ ]
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));
正则表达式测试:https://regex101.com/r/8Ulpu9/1/