Django provides two way to add custom validation rules to a form.

  1. clean() : If added as a form sub-class, lets you access and validate all fields in the form.
  2. clean_() : Lets you define validation method for the , it’s added as sub-class in form.

Usign clean()

You can have your custom validation code in these classes. Once you detected an invalid data raise error. Use this method if you need to deal with multiple inputs.

raise forms.ValidationError("", code="",)

These functions gives the absolute power to deal with forms. Example usage:

class ContactForm(forms.Form):
 # Form fields
 def clean(self):
  if field < 100:
   raise forms.ValidationError("you can't go below 100", code="field1",)
  return  self.cleaned_data

Using clean_()

If your requirement is to validate a single field this is right solution. It allows all the functions you can do with the clean() but restricts access only to the single field.
Example Usage

class ContactForm(forms.Form):
 # Form fields
 # user_name is the form field 
 def clean_user_name(self):
  user_name = self.cleaned_data['user_name']
  if user_name is None:
   raise forms.ValidationError("Give me a username", code="user_name",)
  return  user_name

Flow of control

You don't have to go for a long vacation to be in a situation where you have to use clean_()& clean() together or clean_() multiple times inside a same form. Here's how they get executed.

  • All clean_() are executed before executing the main clean() function.
  • Once a clean_() is executed the field is removed from the cleaned_data.

If using multiple clean method make sure you check if field exists in the cleaned_data before you grab it, it can result in KeyError if the fields clean method removed it.