英文:
json schema not working for type = number and pattern = 10 digit regular pattern
问题
I am trying to write a jsonschema that works for a phone number which is a number and it should be equal to 10 digit. To achieve this, I have written a JSON schema as given below:
{"title":"Schema","description":"Schema","type":"object","properties":{"phone_number":{"type":"number","pattern":"^[0-9]{10}$"}}}
My request JSON is {"phone_number":123481}
.
Ideally, my JSON schema should throw an exception telling me the phone_number is not 10 digits, but there is no error being thrown. Can somebody tell me what is wrong with this code?
英文:
I am trying to write a jsonschema that works for a phone number which is a number and it should be equal to 10 digit. To achieve this i have written a json schema as given below
{"title":"Schema","description":"Schema","type":"object","properties":{"phone_number":{"type":"number","pattern":"^[0-9]{10}$"}}}.
My request json is {"phone_number":123481}
Ideally my json schema should throw an exception telling me the phone_number is not 10-digit but there is no error which is being thrown. Can somebody tell me what is wrong in this code.
答案1
得分: 4
以下是翻译好的内容:
“JSON模式验证草案规范”在“字符串的验证关键字”下列出了pattern
。 因此,如果您想要验证电话号码,您将不得不将它们记录为string
而不是number
。
换句话说,您的模式应该是
{"title":"模式","description":"模式","type":"object","properties":{"phone_number":{"type":"string","pattern":"^[0-9]{10}$"}}}.
而且您的请求JSON将需要是{"phone_number":"123481"}。
在某些地方(特别是在英国),电话号码可以以零开头,但number
类型无法存储前导零。 此外,例如,123
和0123
作为电话号码可能存在差异,如果使用number
类型,您将无法区分这两者之间的区别。
英文:
The <a href="https://json-schema.org/draft/2019-09/json-schema-validation.html#string">JSON Schema validation draft spec</a> lists pattern
under "Validation Keywords for Strings". Therefore, if you want to validate phone numbers, you will have to record them as string
s, not number
s.
In other words, your schema should be
{"title":"Schema","description":"Schema","type":"object","properties":{"phone_number":{"type":"string","pattern":"^[0-9]{10}$"}}}.
and your request JSON will have to be {"phone_number":"123481"}
.
In certain places (particularly here in the UK), phone numbers can begin with zeroes, but the number
type cannot store leading zeroes. Also, there may be a difference between, for example, 123
and 0123
as a phone numbers, and you would not be able to tell the difference between these two if you used the number
type.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论