![]() |
VOOZH | about |
Custom field validations ensure that data entered into a model field meets specific rules before being saved to the database. They extend Django’s built-in validations, allowing developers to enforce additional rules.
field_name = models.Field(validators=[validator_function1, validator_function2])
Consider a project named 'geeksforgeeks' having an app named 'geeks'. Let’s create a custom validator that accepts only email addresses ending with @gmail.com.
In models.py, start with a simple model having a CharField for email:
Create a custom validator function that will check whether the email address ends with @gmail.com. If it doesn't, the function will raise a ValidationError.
Attach this validator function to the geeks_mail field in model using the validators parameter.
After every change in models.py, run these commands makemigrations and migrate commands to update the changes in database.
Validation can be tested interactively by the Django shell:
python manage.py shell
This allows creating model instances and checking how Django responds to valid and invalid input.
If a value like "abc@geeksforgeeks.org" is used for geeks_mail, the custom validation system will raise an error, as only addresses ending with @gmail.com are allowed.
Values that satisfy the custom validator (ending with @gmail.com) will not raise any ValidationError.
The Django admin interface can be used to verify that non-Gmail email addresses are automatically rejected, as the custom validator enforces the required validation rule.