I am storing a phone number in model
like this:
phone_number = models.CharField(max_length=12)
User would enter a phone number and I would use the phone number for SMS Authentication
This application would be used globally. So I would also need country code. Is CharField
a good way to store phone number? And, how do I validate the phone number?
Thanks in advance.
Use django-phonenumber-field: https://github.com/stefanfoulis/django-phonenumber-field
Use
CharField
for phone field in the model and thelocalflavor
app for form validation:https://docs.djangoproject.com/en/1.7/topics/localflavor/
Validation is easy, text them a little code to type in. A CharField is a great way to store it. I wouldn't worry too much about canonicalizing phone numbers.
I will describe what I use:
Validation: string contains more than 5 digits.
Cleaning: removing all non digits symbols, write in db only numbers. I'm lucky, because in my country (Russia) everybody has phone numbers with 10 digits. So I store in db only 10 diits. If you are writing multi-country application, then you should make a comprehensive validation.
Rendering: I write custom template tag to render it in template nicely. Or even render it like a picture - it is more safe to prevent sms spam.
You might actually look into the internationally standardized format E.164, recommended by Twilio for example (who have a service and an API for sending SMS or phone-calls via REST requests).
This is likely to be the most universal way to store phone numbers, in particular if you have international numbers work with.
1. Phone by PhoneNumberField
You can use
phonenumber_field
library. It is port of Google's libphonenumber library, which powers Android's phone number handling https://github.com/stefanfoulis/django-phonenumber-fieldIn model:
In form:
Get phone as string from object field:
Normolize phone string (for tests and other staff):
2. Phone by regexp
One note for your model: E.164 numbers have a max character length of 15.
To validate, you can employ some combination of formatting and then attempting to contact the number immediately to verify.
I believe I used something like the following on my django project:
EDIT
It appears that this post has been useful to some folks, and it seems worth it to integrate the comment below into a more full-fledged answer. As per jpotter6, you can do something like the following on your models as well:
models.py:
It all depends in what you understand as phone number. Phone numbers are country specific. The localflavors packages for several countries contains their own "phone number field". So if you are ok being country specific you should take a look at localflavor package (
class us.models.PhoneNumberField
for US case, etc.)Otherwise you could inspect the localflavors to get the maximun lenght for all countries. Localflavor also has forms fields you could use in conjunction with the country code to validate the phone number.