closeio / cleancat

Validation and serialization library for Python designed to be used with JSON REST frameworks
MIT License
52 stars 7 forks source link

PhoneNumber schema #4

Open philfreo opened 10 years ago

philfreo commented 10 years ago

Rather than having to rely on a Mongoengine field for validating phone numbers, this should be handled at the schema level

mattjegan commented 7 years ago

@philfreo I may have some time to look into this. Phone numbers however can come in all shapes and sizes, making it pretty hard to comprehensively validate them all. What level of validation were you hoping for? Checking that it's just a string of numbers? or some country specifically?

wojcikstefan commented 7 years ago

We've successfully relied in production on this validation of a custom MongoEngine PhoneField: https://github.com/closeio/flask-common/blob/5199233025b959424473588e9e999929aeaf5144/flask_common/fields.py#L140

It utilizes https://github.com/daviddrysdale/python-phonenumbers for most of the parsing/validation logic.

I haven't fully thought this through and I'm open to suggestions, but at a glance a cleancat Phone field could follow a very similar logic with a strict=False/True (where False is the default) kwarg.

Perhaps it would also be worth it to have a region kwarg, which you can then pass to phonenumber.parse. It should allow callables so that you can have a function determining the region based on the current request's context (e.g. if current_user has a specific country preference). From the phonenumbers.parse docstring:

region -- The region that we are expecting the number to be from. This
          is only used if the number being parsed is not written in
          international format. The country_code for the number in
          this case would be stored as that of the default region
          supplied. If the number is guaranteed to start with a '+'
          followed by the country calling code, then None or
          UNKNOWN_REGION can be supplied.