Django - Adding password validations in a ModelForm
in forms.py file you can use this to validate the password for all validations which have been defined in settings. if you didn't define any of the validators in the settings file then call a specific validator which you want to validate.
from django.contrib.auth.password_validation import validate_password`
from django.core import validators
from django import forms
class User_profileForm(forms.ModelForm):
password=forms.CharField(widget=forms.PasswordInput,validators=[validate_password])
You'll want to read the Django documentation about Password Validation.
To summarize, you'll need to update the AUTH_PASSWORD_VALIDATORS
setting in your settings.py
.
Django comes with a few built-in password validators:
UserAttributeSimilarityValidator
(checks for similarity between the password and a set of attributes of the user)MinimumLengthValidator
(checks whether the password meets a minimum length)CommonPasswordValidator
(checks whether the password occurs in a list of common passwords)NumericPasswordValidator
(checks whether the password isn’t entirely numeric)
Based on the example validations you state in your question, you'll want to use the MinimumLengthValidator
and the UserAttributeSimilarityValidator
.
Since you are using a form, you need to manually trigger the password validation as described in the Django docs) by calling django.contrib.auth.password_validation.validate_password
when you validate the form.