Skip to content

Commit

Permalink
Merge pull request #250 from volunteers-for-city-projects/validate_ad…
Browse files Browse the repository at this point in the history
…dress

Added address_line validation and strip multiple spaces
  • Loading branch information
1yunker authored Nov 28, 2023
2 parents 1362c7d + 91b39b8 commit 1254ba1
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 1 deletion.
4 changes: 4 additions & 0 deletions backend/api/serializers.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import re

from django.conf import settings
from django.contrib.auth import get_user_model
from django.db import transaction
Expand Down Expand Up @@ -430,6 +432,7 @@ def create(self, validated_data):
address, _ = Address.objects.get_or_create(
**validated_data.pop('event_address')
)
address.address_line = re.sub(' +', ' ', address.address_line)
project_instanse = Project.objects.create(
event_address=address, **validated_data
)
Expand All @@ -443,6 +446,7 @@ def update(self, instance, validated_data):
address = instance.event_address
for attr, value in address_data.items():
setattr(address, attr, value)
address.address_line = re.sub(' +', ' ', address.address_line)
address.save()
return super(ProjectSerializer, self).update(instance, validated_data)

Expand Down
4 changes: 3 additions & 1 deletion backend/projects/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from .validators import (
LengthValidator,
regex_string_validator,
validate_address,
validate_name,
validate_ogrn,
validate_phone_number,
Expand Down Expand Up @@ -212,7 +213,8 @@ class Address(models.Model):
"""

address_line = models.CharField(
max_length=100, verbose_name='Адрес в одну строчку'
max_length=100, verbose_name='Адрес в одну строчку',
validators=[validate_address]
)
street = models.CharField(max_length=75, verbose_name='Улица')
house = models.CharField(max_length=5, verbose_name='Дом')
Expand Down
26 changes: 26 additions & 0 deletions backend/projects/validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -223,3 +223,29 @@ def validate_text_field(value):
min_length_validator(value)
max_length_validator(value)
regex_validator(value)


def validate_address(value):
"""
Валидация адреса.
"""
MIN_LEN = 2
MAX_LEN = 100
NAME_REGEX = r'^[A-Za-zА-Яа-я0-9 ,-.]+$'

min_length_validator = MinLengthValidator(
MIN_LEN,
message=f'Минимальная длина поля должна быть: {MIN_LEN}.',
)
max_length_validator = MaxLengthValidator(
MAX_LEN,
message=f'Максимальная длина поля должна быть: {MAX_LEN}.',
)
regex_validator = RegexValidator(
regex=NAME_REGEX,
message='Недопустимые символы в адресе. Разрешены латинские '
'и кириллические буквы, цифры, пробел, запятая, точка и тире.',
)
min_length_validator(value)
max_length_validator(value)
regex_validator(value)

0 comments on commit 1254ba1

Please sign in to comment.