簡體   English   中英

節點打字稿:正則表達式允許至少一個帶有 joi 驗證的字母字符的空格

[英]node typescript : regex to allow whitespace with at least one alphanum caracter with joi validation

我正在使用 joi 和 regex 來驗證用戶輸入,我只想接受可以允許空格的字母數字字符。 我做了以下事情:

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/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM