Как добавить валидатор мобильного номера в модель Django?
def validate_mobile_number(value):
if not str(value).isdigit():
raise ValidationError("Please Enter Valid Mobile Number")
class ModelA(AbstractUser):
mobile = models.CharField(_("Mobile"), unique=True, max_length=10,validators[validate_mobile_number,validators.MinLengthValidator(limit_value=10)])
def validate_mobile_number(value):
if not str(value).isdigit():
raise ValidationError("Please Enter Valid Mobile Number")
class ModelA(AbstractUser):
mobile = models.CharField(_("Mobile"), unique=True, max_length=10,
validators[validate_mobile_number,
validators.MinLengthValidator(limit_value=10)])
Если вы используете его с шаблоном и ModalForm, вы можете добавить функцию 'clean_mobile' для валидации mobile.
class ModalAForm(form.ModalForm):
class Meta:
modal = ModalA
fields = '__all__'
def clean_mobile(self):
mobile = self.cleaned_data['mobile']
if not mobile.isdigit():
raise forms.ValidationError('Please Enter Valid Mobile Number')
return mobile
или, если вы используете его с api вызовами, вы можете добавить то же самое в класс modalserializer с именем функции 'validate_mobile', как
def validate_mobile(self, value):
if not value.isdigit():
raise serializers.ValidationError('Please Enter Valid Mobile Number')
return value