Validating form with jQuery-Ajax

When it comes to the usual POST, GET methods, I usually know my way.

However, implementing ajax-jQuery in my form validation code is a huge step for me.

I have a form that has 3 fields: email address, email confirmation and password.

I use this form to register a new user.

form.py

class UserField(forms.EmailField):
    def clean(self, value):
        super(UserField, self).clean(value)
        try:
            User.objects.get(username=value)
            raise forms.ValidationError("email already taken.")
        except User.DoesNotExist:
            return value

class RegistrationForm(forms.Form):

    email = UserField(max_length=30, required = True)
    conf_email = UserField(label="Confirm Email", max_length=30, required = True)
    password = forms.CharField(label="Enter New Password", widget=forms.PasswordInput(), required=True)

    def clean(self):
        if 'email' in self.cleaned_data and 'conf_email' in self.cleaned_data:
            if self.cleaned_data['email'] != self.cleaned_data['conf_email']:
                self._errors['email'] = [u'']
                self._errors['conf_email'] = [u'Email must match.']
        return self.cleaned_data

HTML code

<form method="post">
    {{ register_form.as_p() }}
    <input name = "Register" type="submit" value="Register" />
</form>

I would like before I click the submit button to check if the form is valid and display any relevant messagesusing ajax-jQuery methods. However, I do not know how to start / do this.

+5
source share

All Articles