2018-04-27 03:27:16 +00:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
#
|
2021-09-15 13:00:54 +00:00
|
|
|
import re
|
|
|
|
|
2023-04-07 13:25:26 +00:00
|
|
|
import phonenumbers
|
|
|
|
|
2018-04-27 03:27:16 +00:00
|
|
|
from django.core.validators import RegexValidator
|
2020-10-29 11:16:32 +00:00
|
|
|
from django.utils.translation import ugettext_lazy as _
|
2019-06-13 10:58:43 +00:00
|
|
|
from rest_framework.validators import (
|
|
|
|
UniqueTogetherValidator, ValidationError
|
|
|
|
)
|
2020-10-27 11:54:41 +00:00
|
|
|
from rest_framework import serializers
|
2023-04-10 09:24:17 +00:00
|
|
|
from phonenumbers.phonenumberutil import NumberParseException
|
2020-10-27 11:54:41 +00:00
|
|
|
|
|
|
|
from common.utils.strings import no_special_chars
|
2018-04-27 03:27:16 +00:00
|
|
|
|
2019-06-13 10:58:43 +00:00
|
|
|
alphanumeric = RegexValidator(r'^[0-9a-zA-Z_@\-\.]*$', _('Special char not allowed'))
|
|
|
|
|
2021-10-14 14:27:02 +00:00
|
|
|
alphanumeric_re = re.compile(r'^[0-9a-zA-Z_@\-\.]*$')
|
|
|
|
|
2021-12-20 10:24:16 +00:00
|
|
|
alphanumeric_cn_re = re.compile(r'^[0-9a-zA-Z_@\-\.\u4E00-\u9FA5]*$')
|
|
|
|
|
|
|
|
alphanumeric_win_re = re.compile(r'^[0-9a-zA-Z_@#%&~\^\$\-\.\u4E00-\u9FA5]*$')
|
2021-10-14 14:27:02 +00:00
|
|
|
|
2019-06-13 10:58:43 +00:00
|
|
|
|
|
|
|
class ProjectUniqueValidator(UniqueTogetherValidator):
|
2020-11-20 07:23:33 +00:00
|
|
|
def __call__(self, attrs, serializer):
|
2019-06-13 10:58:43 +00:00
|
|
|
try:
|
2020-11-20 07:23:33 +00:00
|
|
|
super().__call__(attrs, serializer)
|
2019-06-13 10:58:43 +00:00
|
|
|
except ValidationError as e:
|
|
|
|
errors = {}
|
|
|
|
for field in self.fields:
|
|
|
|
if field == "org_id":
|
|
|
|
continue
|
|
|
|
errors[field] = _('This field must be unique.')
|
|
|
|
raise ValidationError(errors)
|
2020-10-27 11:54:41 +00:00
|
|
|
|
|
|
|
|
|
|
|
class NoSpecialChars:
|
|
|
|
def __call__(self, value):
|
|
|
|
if not no_special_chars(value):
|
|
|
|
raise serializers.ValidationError(
|
|
|
|
_("Should not contains special characters")
|
|
|
|
)
|
2021-09-15 13:00:54 +00:00
|
|
|
|
|
|
|
|
|
|
|
class PhoneValidator:
|
|
|
|
message = _('The mobile phone number format is incorrect')
|
|
|
|
|
|
|
|
def __call__(self, value):
|
2023-04-10 09:24:17 +00:00
|
|
|
try:
|
2023-04-10 09:31:53 +00:00
|
|
|
phone = phonenumbers.parse(value, 'CN')
|
2023-04-10 09:24:17 +00:00
|
|
|
valid = phonenumbers.is_valid_number(phone)
|
|
|
|
except NumberParseException:
|
|
|
|
valid = False
|
|
|
|
|
2023-04-10 09:57:09 +00:00
|
|
|
if not valid:
|
2021-09-15 13:00:54 +00:00
|
|
|
raise serializers.ValidationError(self.message)
|