【问题标题】:node typescript : regex to allow whitespace with at least one alphanum caracter with joi validation节点打字稿:正则表达式允许带有至少一个带有 joi 验证的字母数字字符的空格
【发布时间】:2020-09-08 16:56:01
【问题描述】:

我正在使用 joi 和正则表达式来验证用户输入,我想只接受可以允许空格的 alpha num 字符。我做了以下事情:

const schema = Joi.object({
  value: Joi.string()
    .regex(
      /^[a-zA-Z0-9 ]*$/,
      'message',
    )
    .max(100)
    .required()
...

问题是现在我允许用户填充仅由空格组成的完整字符串,这不是我想要的,我接受空格,只有当它们位于字母字符之间时。我用这个来测试:https://www.regextester.com/104025

【问题讨论】:

    标签: javascript node.js typescript joi


    【解决方案1】:

    试试这个:

    /^[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/

    【讨论】:

      【解决方案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/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多