Custom Field Validations in Django Forms
This article revolves around how to add custom validation to a particular field. For example to add validation of an email to a CharField by specifying a particular format. There can be multiple ways on how to achieve custom validation. In this article, we are going to show it from the form itself so that you need not manipulate it elsewhere.
What is Validators ?
A validator is a callable that takes a value and raises a ValidationError if it doesn’t meet criteria. Validators can be useful for re-using validation logic between different types of fields.
Django Custom Field Validation Explanation for Django Forms
Illustration of validators using an Example. Consider a project named geeksforgeeks having an app named geeks.
Refer to the following articles to check how to create a project and an app in Django.
To use built-in Validators in your forms field, import validators in forms.py like this.
call built-in MaxLengthValidators from validators, it raises validation error if the length of the value is greater than limit_value.
How to create our custom validators in django ?
So we are going to create our own custom validators.
Example 1 :-
We will create a validator, if name is not start with s it will raise a an error.
Pass the function in validators.
We write a logic if a name doesn’t start with ‘s’ it raise an error and wrap in function.
Example 2 :-
We will create a validator for a mobile number field
We write a logic of mobile number validator it raise an error and wrap in function