3

How can I add a custom error message in a Django form?

For example, I want to add a new error message in a view if two e-mails aren't the same.

1 Answer 1

13

First you must define a function that begins with clean_[your field name] --- for example: def clean_email. Then write your validation in your function and assign an error name and use it in error_messages of your field.

class ValidationForm(forms.Form):
    email = forms.EmailField(label = 'Email', error_messages = {'invalid': 'Your Email Confirmation Not Equal With Your Email'})
    email_confirmation = forms.EmailField(label = 'Email Confirmation')

    def clean_email(self):
       if email != email_confirmation:
          raise ValidationError(self.fields['email'].error_messages['invalid'])
       return email    
Sign up to request clarification or add additional context in comments.

2 Comments

Note you'll need to use the cleaned dictionary, in this case self.cleaned_data['email'], to get the user values (docs.djangoproject.com/en/dev/ref/forms/validation/…)
I think you meant to say that you should define a 'method' not 'function'. Thanks, though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.