When creating an application with Django alone, it may be better to validate with form, but if you mainly provide API as Django REST Framework, you also want to validate with Model Below is an example of validating phone number and zip code fields
models.py
from django.db import models
from django.core.validators import RegexValidator
class SampleModel(model.model):
tel_number_regex = RegexValidator(regex=r'^[0-9]+$', message = ("Tel Number must be entered in the format: '09012345678'. Up to 15 digits allowed."))
tel_number = models.CharField(validators=[tel_number_regex], max_length=15, verbose_name='phone number')
postal_code_regex = RegexValidator(regex=r'^[0-9]+$', message = ("Postal Code must be entered in the format: '1234567'. Up to 7 digits allowed."))
postal_code = models.CharField(validators=[postal_code_regex], max_length=7, verbose_name='Postal code')
This way you can validate with regular expressions If you send a request that does not match, the message set for each will be returned.
If you want to save the record with a hyphen, it is better to write a regular expression suitable for it in regex =
As an aside, I wish I could set max_length when I defined each regular expression, but I couldn't.
Recommended Posts