Browse Source

Name and phone number validation added

TonyKurts 1 month ago
parent
commit
d21e0375cd
1 changed files with 29 additions and 6 deletions
  1. 29 6
      models.py

+ 29 - 6
models.py

@@ -1,14 +1,37 @@
+import re
+
 from django.db import models
 from django.db import models
 from django.contrib.auth.models import AbstractUser
 from django.contrib.auth.models import AbstractUser
+from django.core.exceptions import ValidationError
+
+
+# Валидатор, разрешающий русские и английские буквы и тире
+def validate_name(value):
+    if not re.match(r'^[a-zA-Zа-яА-Я-]+$', value):
+        raise ValidationError(
+            'Поле может содержать только русские/английские буквы и тире.',
+            params={'value': value},
+        )
+
+# Валидатор для номера телефона
+def validate_phone_number(value):
+    if (not re.match(r'^\d+$', value)) or (len(value) < 11):
+        raise ValidationError(
+            'Номер телефона должен состоять минимум из 11 цифр.',
+            params={'value': value},
+        )
 
 
 
 
 class ShariXUser(AbstractUser):
 class ShariXUser(AbstractUser):
-    middle_name = models.CharField(max_length=150, null=True, blank=True, verbose_name="Отчество")
-    phone_number = models.CharField(max_length=18, unique=True, verbose_name="Номер телефона")
-    avatar = models.ImageField(upload_to="user_avatars/", null=True, blank=True, verbose_name="Аватар")
+    last_name = models.CharField("Фамилия", max_length=150, validators=[validate_name])
+    first_name = models.CharField("Имя", max_length=150, validators=[validate_name])
+    middle_name = models.CharField("Отчество", max_length=150, blank=True, null=True, validators=[validate_name])
+    phone_number = models.CharField("Номер телефона", max_length=13, unique=True, validators=[validate_phone_number])
+    email = models.EmailField("Адрес электронной почты")
+    avatar = models.ImageField("Аватар", upload_to="user_avatars/", null=True, blank=True)
 
 
-    USERNAME_FIELD = "phone_number"
-    REQUIRED_FIELDS = ['username', 'first_name', 'last_name']
+    USERNAME_FIELD = 'phone_number'
+    REQUIRED_FIELDS = ['first_name', 'last_name', 'username', 'email']
 
 
     def __str__(self):
     def __str__(self):
-        return f"{self.first_name} {self.last_name}{' ' + self.patronymic if self.patronymic else ''}"
+        return f"{self.first_name} {self.last_name}{' ' + self.middle_name if self.middle_name else ''}"