JSON SCHEMA: Can we do an either/or (string/int) f

2019-05-11 11:46发布

I'm doing a schema to validate contact information.
In the phone number validation, we have a country code.
I am really hoping there's a way to allow the country code to either be a string or an integer.

Users from different countries inform me that there are sometimes meaningful non-integer characters in the country code (such as a "+"). That being said, a string makes sense.
On the other hand, if someone provides a country code as an int, say .. something like 33 (france), I feel it'd be a bit ridiculous, almost pretentious, to throw a failure alert and force them to cast it as a string and re-send it as "33".

I would like to enforce type constraints to ensure that someone does not try to send an object or array, but I need to allow it to be one of either a string or an integer.
How can this be done?

2条回答
Deceive 欺骗
2楼-- · 2019-05-11 12:03

You have several options, please have a look at the docs:

  • Use pattern property, and use a regular expression to enforce valid code.
  • Use anyOf with two schemas. Each schema will validate integer or string type.
  • If you have all country codes (very easy to get) you might enforce exact values with an enum list.
查看更多
劳资没心,怎么记你
3楼-- · 2019-05-11 12:12

You can validate multiple types using :

"type": ["integer", "string"]

More info: https://cswr.github.io/JsonSchema/spec/multiple_types/

查看更多
登录 后发表回答