Form validation using jQuery-Ajax
When it comes to normal POST, GET methods, I usually know my way around.
However, implementing ajax-jQ开发者_Go百科uery 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.
You might want to look into http://github.com/alex/django-ajax-validation
There is some documentation here and here
You might also look at errors handling with AJAX. http://garmoncheg.blogspot.com/2013/11/ajax-form-in-django-with-jqueryform.html It has an accent on how to do it with jQuery form plugin and a dummy views/urls config in order for your task to work. (At least very similar one)
精彩评论