Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Form validation using jQuery-Ajax

Tags:

jquery

django

When it comes to normal POST, GET methods, I usually know my way around.

However, implementing ajax-jQuery into my code to make form validation is proving a huge step for me to learn.

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

I am using 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 that, before I press the submit button, to check if the form is valid and display any relevant error messages, by using ajax-jQuery methods. However, I have no idea how to start / do this.

like image 631
Nelson_Wu Avatar asked Oct 11 '22 13:10

Nelson_Wu


1 Answers

You might want to look into http://github.com/alex/django-ajax-validation

There is some documentation here and here

like image 178
DrMeers Avatar answered Nov 15 '22 09:11

DrMeers