0

I am trying to do validation for model forms to check if both 'email' and 'confirm_email' have same value. I tried searching online but getting some errors. I am making custom validators in models.py file.

Can you please help me with that. What would be the best way of validating model forms.

Here is my code.

MODELS.PY

from django.db import models

from django.core import validators

from django.core.exceptions import ValidationError
# Create your models here.
def validate_equal(self, email, confirm_email):
    if email != confirm_email:
        raise ValidationError(
        ('email does not match'),
        params={'email': email, 'confirm_email': confirm_email}
        )

class NewSubscriber(models.Model):
    first_name = models.CharField(max_length=128)
    last_name = models.CharField(max_length=128)
    email = models.EmailField(max_length=254,unique=True)
    confirm_email = models.EmailField(max_length=254, validators=[validate_equal('self', 'email', 'confirm_email')])

1 Answer 1

1

You can't do validation like that, especially when you want to compare fields. All you're doing here is passing the literal strings 'email' and 'confirm_email' (as well as 'self', for some reason) - and you're calling the validation function at define time.

Instead, use a clean method on the form itself.

class NewSubscriberForm(forms.ModelForm):
    class Meta:
        fields = '__all__'

    def clean(self):
        if self.cleaned_data['email'] != self.cleaned_data['confirm_email']:
            raise forms.ValidationError('email does not match')
        return self.cleaned_data
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the help Daniel!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.