Custom Validation in Django newforms library

This is how you add your own additional validation logic to a form in the newforms library:

Create a clean_XXXX method in your forms class. This will be called by the forms validation logic. Subsitute XXXX with the field name. Inside this method you will have access to all forms data clean’ed so far, including the field in question. After performing any custom validation, either returned the cleaned and validated data, or raise ValidationError.

Note: The ValidationError type is now from django.newforms.util, not from django.core.validators. Be careful with that.

This is the typical user registration type form as an example:

 

from django import newforms as forms
from django.newforms.util import ValidationError

class RegForm(forms.Form):
     username = forms.CharField( max_length=30),
     email = forms.EmailField(max_length=256),
     password1 = forms.CharField(max_length=16,widget=forms.PasswordInput)
     password2 = forms.CharField(max_length=16,widget=forms.PasswordInput)

     def clean_username(self):
          n = self.clean_data[’username’]
          try:
                  User.objects.get(username=n)
          except User.DoesNotExist:
                  return

          raise ValidationError(’The username “%s” is already taken.’ % n)

     def clean_password2(self):
          if self.clean_data[’password1?] != self.clean_data[’password2?]:
               raise ValidationError(’Passwords must match.’)
          else:
               return self.clean_data['password2']

There are more examples in the test script as well.