6

The title may have been confusing, but please let me explain:

Currently when I am storing phone number with raw digits like 5554441234. Then in my template I was going to "format" the number into something like 555-444-1234.

I realized in Django's localflavor, there is a US phone number field that checks if a string is in XXX-XXX-XXXX format.

So my question is should I enter the phone number as raw digits then format it in the template or should I enter the phone number in the formatted way using localflavor?

If I choose the latter, would the XXX-XXX-XXXX format restriction apply even to the database API level or in the Django admin page?

hobbes3
  • 28,078
  • 24
  • 87
  • 116

3 Answers3

9

Store them as entered, only strip surrounding white space if necessary. The way a user formats its number stores semantic information that you do not want to lose by normalizing it. In the US the format XXX-XXX-XXXX is very common, but other locales use totally different formats. For example, where I live some common formats are: XX-XXX XXX XX, XXX/XXX XX XX, +46(0)70-XXX XX XX and so on ad nausem.

The number displayed to the user should be in the same format as entered, otherwise he or she will think of it as munged or may not even recognize the number if it is formatted in a different style than the user is used to. See also this discussion: http://discuss.fogcreek.com/dotnetquestions/default.asp?cmd=show&ixPost=6079&ixReplies=6

Björn Lindqvist
  • 19,221
  • 20
  • 87
  • 122
  • How would I check in the Django admin? Is there a way to tag the `CharField` to enforce the `XXX-XXX-XXXX` validation on a `models.py` level? – hobbes3 Mar 30 '12 at 16:09
  • 3
    The point is that you should **not** try to enforce it. It's not your site's business to tell users how they should format their own phone numbers. – Björn Lindqvist Apr 01 '12 at 11:13
2

If you're using forms framework (for example, in the Django admin), the validation of the input will be done on the application level. So, to enter phone number in the form, you have to format it to XXX-XXX-XXXX.

On the database level, it's just a CharField, so database doesn't do any checks for the format.

gakhov
  • 1,925
  • 4
  • 27
  • 39
  • 1
    If you want to validate on `models.py` level, you can attach your function to `pre_save` signal for the model. In that function you can use `localflavor` for validate the input. – gakhov Mar 30 '12 at 16:24
0

Try Django-phoneno. field . It is available on Python website. You need to install using pip install django-phonenumber-field

https://pypi.python.org/pypi/django-phonenumber-field/0.2a3