通过 json 模式验证正则表达式输入

Validation of regex input through json schema

我必须从 html 页面接受 regular expression 作为用户的输入。我正在使用 spring 启动后端 json 模式验证

Pattern.compile(regex);

java 中的方法作为后端,如果它不是有效的正则表达式,将抛出错误。如果它是一个有效的正则表达式,这将不会抛出任何错误。

我们可以用 json 模式做同样的事情来验证正则表达式输入而不使用 java 中的动态方法吗?(这样可以减少测试用例的数量)

我们如何仅使用 json 架构来实现这一点?

通过 json 模式验证正则表达式输入

到 accept/validate 包含正则表达式输入字段的请求正文。通常我们必须使用 Pattern.compile(myRegex) ,其中 myRegex 是正则表达式的输入字段。如果它抛出错误(例如,PatternSyntaxException In java),它是无效的,否则它是有效的正则表达式。


这也可以在 json 架构中完成

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "description": "This is for validating input json request body containing myRegex field which accepts regex",
  "required": [
    "myRegex"
  ],
  "properties": {
    "myRegex": {
      "type": "string",
      "format": "regex"
    }
  }
}

此架构验证以下 POST/PUT

的请求主体
{

    "myRegex":"*8"
}

上述请求正文无效,因为“*8”不是有效的正则表达式


{

    "myRegex":"^[_A-Za-z0-9][-_A-Za-z0-9.]*$"
}

根据架构,这是有效的


参考: https://json-schema.org/understanding-json-schema/reference/string.html#format

"regex" 属性已在草案 7 中新引入