Python Validator function for phone and email

Viewed 133

I have a website to validate spreadsheet headers and rows when a spreadsheet is uploaded to the site, here I have some validation function where I will have to validate the rows according the attributes of the field in my case I have model like below:

models.py

from phone_field.models import PhoneField

class Add(Model):
    phone = PhoneField(max_length=255)
    a_1 = models.CharField(max_length=255)
    ad_2 = models.CharField(max_length=255)
    town = models.CharField(max_length=255)
    email = models.EmailField(unique=True)

I need to write the custom validators for phone and email while uploading the spreadsheet.

def phone_validator(value):
    # code: ...
def email_validator(value):
    # code: ...
2 Answers

You don't have to write validators. The entire point of an EmailField and a PhoneField is that it contains validators. For example an EmailField [Django-doc] is:

A CharField that checks that the value is a valid email address using EmailValidator.

The EmailField will thus validate that the value entered is an email address.

You furthermore do not have to validate unique=True [Django-doc] either:

This is enforced at the database level and by model validation. If you try to save a model with a duplicate value in a unique field, a django.db.IntegrityError will be raised by the model’s save() method.

So Django will automatically validate the uniqness as well.

For a PhonreField, it will; not add validation by default, since there are a lot of ways to specify a phone number. If you want to only allow phone numbers by the E.164 standard [wiki], you can set E164_only=True for that field:

from phone_field.models import PhoneField

class Address(BaseModel):
    phone = PhoneField(E164_only=True, blank=True)
    # …

but personally I would not do that. If you do not set the max_length=… parameter [Django-doc], it will use max_length=31, which is likely sufficient for a phone number. The length is also validated. Indeed, as the documentation on the max_length=… parameter says:

Required. The maximum length (in characters) of the field. The max_length is enforced at the database level and in Django’s validation using MaxLengthValidator.

So to summarize, only for a field that requires some non-standard validation, you need to implement a custom validator.

You can see the Django document about the validators

https://docs.djangoproject.com/en/4.0/ref/validators/

also, you can use this one

https://www.programcreek.com/python/example/63699/django.core.validators.validate_email
Related