Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django form field regex validation for alphanumeric characters [duplicate]

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

like image 215
MHS Avatar asked Apr 25 '15 12:04

MHS


2 Answers

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")])
like image 162
M.javid Avatar answered Oct 25 '22 20:10

M.javid


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
like image 34
skyline75489 Avatar answered Oct 25 '22 20:10

skyline75489