Reputation: 2078
I have a custom password form field. Now when i have 2 password fields and the password doesnt meet requirements. Both fields report the error.
Is there a way I can remove this error in case it has already occurred on the first field?
class PasswordField(forms.CharField):
def validate(self, value):
super(PasswordField, self).validate(value)
if not value or re.match("^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d!.@#$%^&*()?<>]{8,}$", value):
return value
raise forms.ValidationError(_("The password does not match the requirements. "
"It should be at least 8 characters long, contain 1 Uppercase letter, "
"1 lowercase letter and 1 number."))
class PasswordForm(forms.Form):
password = PasswordField(widget=forms.PasswordInput(), label="Password", required=True)
password_2 = PasswordField(widget=forms.PasswordInput(), label="Confirm Password", required=True)
Upvotes: 0
Views: 58
Reputation: 43300
Either move your logic into the PasswordForm
's clean_password
method, or write it as a validator and then apply this validator to the first password field.
def validate_password(value):
if not value or re.match("^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d!.@#$%^&*()?<>]{8,}$", value):
return value
raise forms.ValidationError(_("The password does not match the requirements. "
"It should be at least 8 characters long, contain 1 Uppercase letter, "
"1 lowercase letter and 1 number."))
password = PasswordField(widget=forms.PasswordInput(), label="Password", required=True, validators=[validate_password])
Note, note you may want to use django's validate_password
and then move possibly move your logic into your own custom validator.
Otherwise, to keep the logic in the field, just make your password_2
a CharField
that uses the PasswordInput
widget so that you only use one of your custom fields in the form.
Upvotes: 1