feat: 手机号支持选择区号

pull/10151/head^2
jiangweidong 2023-04-07 21:25:26 +08:00 committed by Jiangjie.Bai
parent ec2c8538d9
commit 7833433d5f
3 changed files with 15 additions and 2 deletions

View File

@ -2,6 +2,8 @@
#
import re
import phonenumbers
from django.core.validators import RegexValidator
from django.utils.translation import ugettext_lazy as _
from rest_framework.validators import (
@ -42,9 +44,9 @@ class NoSpecialChars:
class PhoneValidator:
pattern = re.compile(r"^1[3456789]\d{9}$")
message = _('The mobile phone number format is incorrect')
def __call__(self, value):
if not self.pattern.match(value):
phone = phonenumbers.parse(value)
if not phonenumbers.is_valid_number(phone):
raise serializers.ValidationError(self.message)

View File

@ -1,5 +1,7 @@
# -*- coding: utf-8 -*-
#
import phonenumbers
from functools import partial
from django.utils.translation import ugettext_lazy as _
@ -222,6 +224,14 @@ class UserSerializer(RolesSerializerMixin, CommonBulkSerializerMixin, serializer
attrs.pop("password_strategy", None)
return attrs
def to_representation(self, instance):
data = super().to_representation(instance)
phone = phonenumbers.parse(data['phone'], 'CN')
data['phone'] = {
'code': '+%s' % phone.country_code, 'phone': phone.national_number
}
return data
def save_and_set_custom_m2m_fields(self, validated_data, save_handler, created):
m2m_values = {}
for f, default_roles in self.custom_m2m_fields.items():

View File

@ -29,6 +29,7 @@ pycparser==2.21
cryptography==38.0.4
pycryptodome==3.15.0
pycryptodomex==3.15.0
phonenumbers==8.13.8
gmssl==3.2.1
itsdangerous==1.1.0
pyotp==2.6.0