Jsonschema:在空字符串或包含空格的字符串上引发错误。

huangapple go评论76阅读模式
英文:

Jsonschema : Throw error on empty string or string with spaces

问题

要求是我有一个名字字段。
对于非空字符串

"properties":{
        "name": {
          "type": "string",
          "minLength": 1
        }
}

对于name = " "(只包含空格的字符串),JsonSchema.validate 通过了。

我想在" "上抛出自定义错误。

英文:

Requirement is I have a name field.
For non empty string

"properties":{
        "name": {
          "type": "string",
          "minLength": 1,
}

JsonSchema.validate is passing for name = " " (string with only empty spaces).

I wan't to throw custom error on " " .

答案1

得分: 3

使用pattern关键字与符合您要求的正则表达式匹配。类似于"pattern": "\S+"

有关pattern关键字的更多信息,请查看JSON Schema中的正则表达式

正则表达式的速查表

英文:

Use the pattern keyword with a regular expression matching your requirements. Something like "pattern": "\S+".

More about the pattern keyword: Regular Expressions in JSON Schema

A cheatsheet for Regular Expressions.

答案2

得分: 0

自定义错误将取决于您使用的库以及它对此类事物的支持程度。

关于模式,您应该在“name”子模式中添加一个pattern关键字。pattern接受一个ECMAScript正则表达式,并要求字符串与其匹配才能通过验证。您可以使用该正则表达式来检查一个空字符串或空白字符串。

英文:

A custom error is going to depend upon which library you're using and what kind of support it has for that kind of thing.

Regarding the schema, you should add a pattern keyword to the "name" subschema. pattern takes an ecmascript regex and requires that the string match it in order to pass validation. You can use that regex to check for a string that is empty or whitespace.

huangapple
  • 本文由 发表于 2023年6月5日 13:47:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/76403769.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定