Custom Client Side Validation for Parsley in Django

I wrote a post on how to add client side validation for Django Forms. In this post I’ll show you how to add custom client validation to Django Forms. I mean by custom validation is a validation that isn't available in django-parsley, like username availability, password strength, email duplication, etc.. let’s see how to add custom client side validation to Django Form.

@parsleyfyclassUserRegistrationForm(forms.ModelForm):classMeta:...parsley_extras={'password':{'remote':reverse_lazy('validate-password-parsley'),'remote-message':"Password is invalid"},'username':{'remote':reverse_lazy('validate_username_uniqueness'),'remote-message':"User with this username is already exists."},'email':{'remote':reverse_lazy('validate_email_uniqueness'),'remote-message':"User with this email is already exists."},}

In the code above we are adding client custom validation as remote to password, username, and email fields, Did you notice that remote key is holding a URL to Django View? let’s create a complete sample to get our head around it.

Django Password Validation Sample

Django 1.9 introduce built-in password validation, so we can use Django's built-in password validators and write an AJAX view to use it in the custom remote validator, and we will take in mind that if in future you want to build your own password validator as additional to the default ones, our view will be valid.

Because Parsley remote validation need to receive HTTP 2xx status to consider the input value valid other than that input value is invalid, we have created 2 classes ParselyInvalidResponse and ParselyValidResponse that inherit from JsonResponse, then in validate_password_parsely() view function we’ve imported get_default_password_validators() function that return all password validator configure in AUTH_PASSWORD_VALIDATORS, after that we’ll loop over each validator and validate the password, if one of validator found the password invalid, we’ll return empty JSON with 404 HTTP status to tell parsley the password is invalid.

URLs.py

Add custom validator to Django Form

We’ll create simple User Registration form and password will be a required field and we’ll hook the above AJAX validator with it using Parsley remote by using django-parsely parsley_extras.

@parsleyfyclassUserRegistrationForm(forms.ModelForm):...password=forms.CharField(widget=forms.PasswordInput(),required=True)...classMeta:...parsley_extras={'password':{'remote':reverse_lazy('validate-password-parsley'),'remote-message':"Password is invalid"},}

As you can see remote key will hold URL to our AJAX validator, and we can use Django’s reverse_lazy() to get the URL from the URL_patterns, and remote-message key will hold the error message for the invalid value.