Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django confirm password validator

I have a profile settings page where users can change their password and they have to confirm it if they do. I cannot make this a required field, since they dont HAVE to change the password. Is there an example to validate the confirm password IF the password field is not empty? And then to check if they are equal? I was not able to find any such example...

like image 618
KVISH Avatar asked Jul 06 '12 20:07

KVISH


People also ask

How does Django validate username and password?

How To Create Your Own Django Password Validator. If you have more specific needs, you can create your own validators. To do so, simply create your own classes based on object and raise a ValidationError if the entered password fails. class NumberValidator(object): def validate(self, password, user=None): if not re.


1 Answers

Add the following to your form's clean method:

def clean(self):
    password1 = self.cleaned_data.get('password1')
    password2 = self.cleaned_data.get('password2')

    if password1 and password1 != password2:
        raise forms.ValidationError("Passwords don't match")

    return self.cleaned_data

EDIT

The validation error message above will go into non_field_errors. You didn't specify what error message is showing on each password field, but based on context, I would imagine it's a "This field is required" message. If that's the case, make sure that your form fields have required=False when you define them, or if you're working with a form subclass (and can't edit the actual form fields) you can override the __init__ method of the form:

class MyForm(SomeOtherForm):
    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)

        self.fields['password1'].required = False
        self.fields['password2'].required = False
like image 51
Chris Pratt Avatar answered Nov 06 '22 11:11

Chris Pratt