英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论