search

Tuesday, April 8, 2014

django: Show form validation error with AJAX and jQuery

I once had a situation when I submited form with AJAX and if there were validation errors I had to put them at the same place as form was normally submited.

Assume that we have edit_user_data method in the views.py. If edit_form is valid we do some really useful things. If it's not, we should show user form validation errors (btw, I use uni_forms in that example).

Here is our code:

def edit_user_data(request):
# ...
if edit_form.is_valid():
# ...
else:
error_message = dict([(key, [unicode(error) for error in value]) for key, value in edit_form.errors.items()])
return HttpResponse(simplejson.dumps({"result": error_message, }), mimetype='application/json')


error_message is a dictionary which contains all form errors. We use JSON so we could have access to the data like server_response.result[key]. Key is the name of the field.

Here is our javascript code:

$("#edit_form").ajaxSubmit({
url: save_url,
type: 'post',
success: function (server_response) {
// Inform about successfull save
if (server_response.result_success) {
// ...
}
// Remove form errors
$("#edit_form").find(".errorField").remove();
for (var key in server_response.result) {
// Check for proper key in dictionary
if (key in {first_name: 1, last_name: 1, gender: 1, sex: 1, phone: 1, }) {
// Get error message
error = server_response.result[key][0];
// Find related field
field = $("#edit_form").find("#div_id_" + key)
// Attach error message before it
field.before('<p class="errorField"><em></em>' + error + '</p>');
}
}
},
});


#edit_form - id of the submited form, url - where we submit the data to. If AJAX request successfuly was proceed by server (it doesn't matter if user submited valid data or not. It means he does submited something) we now could show user if his form is valid or not. If it is not valid, we remove old errors from form (or we will have multiple errors under the fields, probably duplicates). Let also assume that our form contains 5 fields: first_name, last_name, gender, sex, phone. Here you can see nice trick how to check if a key is related to one of our fields:
if (key in {first_name: 1, second_name: 1, gender: 1, sex: 1, phone: 1, }) {}

We also want to show user only one error per field (If there are more, he will be able to see them next time):
error = server_response.result[key][0];

To show error message above the field itself we need to find that field:
field = $("#edit_form").find("#div_id_" + key)

Luckly our key names are the same as field names :) And then attach a message before it:
field.before('

' + error + '

');

Where error is description of error, for example, "This field is required". Done. Errors looks nice and native ")

No comments:

Post a Comment