[Fixed]-Only show error on one form field

1👍

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.

👤Sayse

Leave a comment