Open In App
Related Articles

Custom Field Validations in Django Forms

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

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.

Python3

from django import forms
from django.core import validators
  
class StuForm(forms.Form):
  name = forms.CharField(
    validators =[validators.MaxLengthValidator(10)])

                    

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.

forms.py

Python3

from django import forms
  
def start_with_s(value):
  if value[0]!='s':
    raise forms.ValidationError("Name should start with s")
  
  
class StuForm(forms.Form):
  name = forms.CharField(
    validators =[start_with_s])

                    

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

Python3

from django import forms
  
def mobile_no(value):
  mobile = str(value)
  if len(mobile) != 10:
    raise forms.ValidationError("Mobile Number Should 10 digit")
  
  
class StuForm(forms.Form):
  mob = forms.IntegerField(
    validators =[mobile_no])

                    

We write a logic of mobile number validator it raise an error and wrap in function



Last Updated : 16 Mar, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads