I have a django form, which contains a password field, I want to validate the field that it must contain a combination of alphabets and numbers.
class AuthorizationForm(forms.Form):
email = forms.CharField()
password = forms.CharField(min_length=7)
I am validating the password field like this:
def clean_password(self):
password = self.cleaned_data['password']
if not re.match(r'^[A-Za-z0-9]+$', password):
raise forms.ValidationError("Password should be a combination of Alphabets and Numbers")
This piece of code isn't working for me, it allows abcdefghij
or 123456789
or abcd123456
, where as I just want to allow abcd123456
You can using RegexValidator
that is a django builtin validator.
Try below code:
from django.core.validators import RegexValidator
class AuthorizationForm(forms.Form):
email = forms.CharField()
password = forms.CharField(min_length=7, validators=[RegexValidator('^(\w+\d+|\d+\w+)+$', message="Password should be a combination of Alphabets and Numbers")])
Regex isn't really necessary, you can simply use string functions to do this:
import string
def validate(password):
letters = set(string.ascii_letters)
digits = set(string.digits)
pwd = set(password)
return not (pwd.isdisjoint(letters) or pwd.isdisjoint(digits))
print(validate('123123')) # False
print(validate('asdfsdf')) # False
print(validate('12312sfdf')) # True
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With