JSON模式在类型为数字且模式为10位数字正则模式时无法正常工作。

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

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类型无法存储前导零。 此外,例如,1230123作为电话号码可能存在差异,如果使用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 strings, not numbers.

In other words, your schema should be

{&quot;title&quot;:&quot;Schema&quot;,&quot;description&quot;:&quot;Schema&quot;,&quot;type&quot;:&quot;object&quot;,&quot;properties&quot;:{&quot;phone_number&quot;:{&quot;type&quot;:&quot;string&quot;,&quot;pattern&quot;:&quot;^[0-9]{10}$&quot;}}}.

and your request JSON will have to be {&quot;phone_number&quot;:&quot;123481&quot;}.

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.

huangapple
  • 本文由 发表于 2020年8月2日 00:44:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/63207660.html
匿名

发表评论

匿名网友

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

确定