Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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 67,989 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