[Django]-How to validate phone number in django?

2👍

Your validation looks correct to me, but you’re doing two things wrong:

  • Rename the method to clean_phone_number() instead of clean_phone. The field is phone_number not phone.
  • Change the field to a CharField instead of IntegerField (too restrictive for many users) and return z.national_number instead of phone_number, that way it’s returning the correctly cleaned number before saving. Or whatever format you want to store it in.

1👍

Set a field with "PhoneNumberField()" in "models.py":

# "models.py"

from django.db import models
from phonenumber_field.modelfields import PhoneNumberField

class MyModel(models.Model):
    phone = PhoneNumberField()

Then, assign the widget "PhoneNumberPrefixWidget()" to the field with an initial country code like initial=’US’ in a custom form and assign the custom form to the admin as shown below. *Initial country code must be uppercase:

# "admin.py"

from django.contrib import admin
from .models import Contact
from django import forms
from phonenumber_field.widgets import PhoneNumberPrefixWidget

class ContactForm(forms.ModelForm):
    class Meta:
        widgets = {                          # Here
            'phone': PhoneNumberPrefixWidget(initial='US'),
        }

@admin.register(Contact)
class ContactAdmin(admin.ModelAdmin):
    form = ContactForm

Now, with the initial country code "US" selected, the field for a phone number is created as shown below so that users don’t need to select a country code by themselves:

enter image description here

0👍

I am not entirely familiar with these packages but after having a look at the repo code behind them it seems like you could just set the region attribute on the PhoneNumberField and keep inheriting all of its validation features and prevent the need for users to type in their region?

Something like this?


class UserRegisterForm(UserCreationForm):
    email = forms.EmailField()
    # Does this not work for your case?
    phone_number = PhoneNumberField(region="SG")

    class Meta:
        model = User
        fields = ['username', 'email', 'phone_number']

    def clean_email(self):
        email = self.cleaned_data.get("email")
        if not validate_email(email, verify=True):
            raise forms.ValidationError("Invalid email")
        return email

Leave a comment