Jazi
Jazi

Reputation: 6732

Django - How to add custom error message in Form?

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.

Upvotes: 3

Views: 11267

Answers (1)

user915370
user915370

Reputation:

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    

Upvotes: 13

Related Questions