Skip to content

Instantly share code, notes, and snippets.

@ryanwitt
Created September 17, 2010 00:27
Show Gist options
  • Save ryanwitt/583437 to your computer and use it in GitHub Desktop.
Save ryanwitt/583437 to your computer and use it in GitHub Desktop.
function setupValidation(field, timeout) {
var input = $('#id_'+field);
var input_tr = $('#id_tr_'+field);
check = function () {
var t = this;
if (this.value != this.lastValue) {
if (this.timer) clearTimeout(this.timer);
input_tr.removeClass('error');
$('#id_tr_errors_'+field).remove();
this.timer = setTimeout(function () {
$.getJSON(
'check?'+field+'='+t.value+'&r='+Math.random(),
function (data) {
datr = data;
if (data.ok) {
} else {
html = '<tr id="id_tr_errors_'+field+'"><th colspan=2><ul class="errorlist">';
for (var i=0; i<data.errors[field].length; i++){
html += '<li>' + data.errors[field][i] + '</li>';
}
html += '</ul></tr>';
input_tr.after(html);
input_tr.addClass('error');
}
}
);
}, timeout);
}
this.lastValue = this.value;
}
input.keyup(check);
input.blur(check);
}
var datr;
/* Example:
$(document).ready(function () {
$('#id_username').focus();
setupValidation('username', 500);
setupValidation('email', 1000);
});
/*
"""
AJAX server side form validation for django.
"""
from django.http import HttpResponse, Http404
from django.utils.encoding import force_unicode
from jsonutil import JsonResponse
def formcheck(request, form_class=None):
"""
This view responds with JSON telling you what form errors
exist in your form before you submit it. Be sure to pass
it the form class that you want to use, e.g.:
urlpatterns += patterns('',
(r'^myformcheck/$', formcheck, {'form': MyForm}),
)
You can use either GET or POST.
"""
form = form_class(request.REQUEST)
form.is_valid()
# Build a dictionary of the errors found in fields that
# were mentioned in the request.
# Note that we have to force unicode here to get the JSON
# serializer not to choke.
errordict = dict(
(
force_unicode(field.name),
[force_unicode(e) for e in field.errors]
)
for field in form
if request.GET.get(field.name) and field.errors
)
return JsonResponse({
'ok': not errordict,
'errors': errordict
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment