如何在django中验证电话号码? [英] How to validate phone number in django?

查看:137
本文介绍了如何在django中验证电话号码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用phonenumbers软件包作为django的UserCreationForm的电话号码字段的验证方法.在当前代码中,我正在使用get方法从其字段中检索电话号码,然后进行验证.如果输入的号码不存在,则应该弹出表格错误,并指出该号码不是国家/地区格式(在这种情况下,我使用的是新加坡).请告诉我应该对当前代码进行哪些更改.

I'm currently using phonenumbers package as a validation method to my django's UserCreationForm for its phone number field. In my current code I am using a get method to retrieve the phone number from its field and then do the validation. If the entered number does not exists, a form error is supposed to pop up and state that the number is not in a country's format (in this case i'm using singapore). Please tell me what changes should be made to my current code.

我尝试使用"from phonenumber_field.formfields import PhoneNumberField"进行电话号码验证,它可以验证我输入的号码,唯一的问题是用户将不得不输入其国家代码,而我不能输入.我只使用电话号码包,这样用户就不必输入国家/地区代码.

I've tried using "from phonenumber_field.formfields import PhoneNumberField" for the phone number validation and it validates the number I've entered, the only problem is that the users will have to type their country code and I cannot have that. I'm using just the phonenumbers package so that users will not have to enter the country code.

/* forms.py */
import phonenumbers
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from validate_email import validate_email
from phonenumber_field.formfields import PhoneNumberField


class UserRegisterForm(UserCreationForm):
    email = forms.EmailField()
    # phone_number = PhoneNumberField()
    phone_number = forms.IntegerField(required=True)

    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

    def clean_phone(self):
        phone_number = self.cleaned_data.get("phone_number")
        z = phonenumbers.parse(phone_number, "SG")
        if not phonenumbers.is_valid_number(z):
            raise forms.ValidationError("Number not in SG format")
        return phone_number

/* views.py */
from django.shortcuts import render, redirect
from django.contrib import messages
from .forms import UserRegisterForm


def register(request):
    if request.method == 'POST':
        form = UserRegisterForm(request.POST)
        if form.is_valid():
            # user = form.save()
            # phone_number = form.cleaned_data['phone']
            # do something with phone number??
            user = form.save()
            user.refresh_from_db()
            phone = form.cleaned_data.get('phone_number')
            user.Meta.phone_number = phone
            user.save()
            username = form.cleaned_data.get('username')
            messages.success(request, f'Account created for {username}!')
            return redirect('blog-home')
    else:
        form = UserRegisterForm()
    return render(request, 'users/register.html', {'form': form})

我希望输出能够验证电话字段中输入的电话号码(不含国家/地区代码,只有8位数字),如果该电话号码不存在,则会引发错误.

I expect the output to validate the entered phone number in the phone field without its country code and only 8 digits and raise an error if that number does not exist.

推荐答案

我对这些软件包并不完全熟悉,但是在查看了它们背后的回购代码之后,似乎可以将region属性设置为PhoneNumberField并继续继承其所有验证功能,并防止用户在其区域中键入文字?

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?

像这样吗?


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

这篇关于如何在django中验证电话号码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆