Question

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?

Was it helpful?

Solution 2

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.

OTHER TIPS

You can validate multiple types using :

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top