Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Django Forms Forms Create a Validator

ValidationError problem

I want to make sure that the email address isn't from any of my coworkers at Treehouse. We'll solve this with a custom validator.

Add a new function named not_treehouse that takes a single argument. If the argument ends with "@teamtreehouse.com", raise aValidationError`. You can use whatever error message you want.

Remember, too, that it's a good idea to standardize your input before testing it, so you might want to lower- or uppercase the value.

def not_treehouse(value):
  value = value.lower()
  if '@teamtreehouse' in value:
    raise ValidationError('email is not valid')


class LeadShareForm(forms.Form):
    email = forms.EmailField(validators=[not_treehouse])
    link = forms.URLField()
    honeypot = forms.CharField(widget=forms.HiddenInput, required=False)

2 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,441 Points

Close but a few corrections needed:

  • check that string is at end of value
  • check '@teamtreehouse.com'
  • use correct path to ValidationError
def not_treehouse(value):
  value = value.lower()
  # check for endswith
  if value.endswith('@teamtreehouse.com'):
    raise forms.ValidationError('email is not valid')

Thank you!

V K
V K
5,237 Points

A quick note to people who might be stumped like I was. The custom validator/function must be outside of the class.
So it should look like this

from django import forms

def not_treehouse(value):
        value = value.lower()
        if value.endswith('@teamtreehouse.com'):
             raise forms.ValidationError('Email is not valid')

class LeadShareForm(forms.Form):
    email = forms.EmailField()
    link = forms.URLField()
    honeypot = forms.CharField(widget=forms.HiddenInput, required=False)


    def clean_honeypot(self):
        honey = self.cleaned_data['honeypot']
        if len(honey):
            raise forms.ValidationError('Bad robot!')
        return honey