Introduction
As the Django documentation says: "A validator is a callable that takes a value and raises a ValidationError
if it doesn’t meet some criteria. Validators can be useful for reusing validation logic between different types of fields."
Yes, you can make your own validator. In this example, I am going to create a password validator that will check if the given password contains at least one letter.
To create a custom validator, create a file called validators.py
within one of your Django applications.
# validators.py
from django.core.exceptions import ValidationError
class ContainsLetterValidator:
def validate(self, password, user=None):
if not any(char.isalpha() for char in password):
raise ValidationError(
'The password must contain at least one letter',
code='password_no_letters'
)
def get_help_text(self):
return 'Your password must contain at least one upper or lower case letter.'
Once you have created the validator, add it to your settings.py file inside the AUTH_PASSWORD_VALIDATORS
dictionary.
# settings.py
AUTH_PASSWORD_VALIDATORS = [
{
"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
"NAME": "app.validators.ContainsLetterValidator",
},
]
The validator is now used to validate the creation of a password.
- official Django documentation about validators
Top comments (0)