thathashd
thathashd

Reputation: 1022

Django Form validation errors handling using AJAX

Having the following form being generated in a Modal:

Template:

...

<div id="form-modal-body" class="modal-body">
            <form id="register_new_customer" method="post" action="{% url "customer:new_customer" %}">
                {% csrf_token %}
                <div id="form-errors" class='form-errors' class="text-danger"></div>
                {%for field in customer_form %}
                    <div class="form-group {%if field.errors %} has-error{%endif%}">
                        <span class="help-block">{{ field.errors }}</span>
                        <label for="{{ field.id_for_label }}" class="control-label">{{ field.label }}</label>
                        <div>{{ field }}</div>
                    </div>
                {% endfor %}
                <div class="modal-footer">
                    <div class="col-lg-10 col-lg-offset-2">
                        <button type="reset" class="btn btn-default" data-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">Submit</button>
                    </div>
                </div>
            </form>
        </div>

...

I'm submitting the form using AJAX as follow:

        $(document).on('submit', '#register_new_customer', function(e) {
        e.preventDefault();
        var frm = $('#register_new_customer')
        $.ajax({
            type: frm.attr('method'),
            url: frm.attr('action'),
            data: frm.serialize(),
            success:function (response) {
                // TODO: How to handle Form Validation error messages?!
            }
        })
        return false;

In my View I'm returning an HttpResponse in case the form is Not Valid:

return HttpResponse(customer_form.errors.as_json())

"phone_number": [{"message": "Please enter a valid Phone Number!", "code": "invalid"}], "box_enabled": [{"message": "This field is required.", "code": "required"}]}

Here I have the error messages and the correspondent Form Field:

How can I pass this error messages correctly to the form html?

Thanks

Upvotes: 1

Views: 1025

Answers (1)

Adam Starrh
Adam Starrh

Reputation: 6958

I think you want something along these lines from your view:

from django.http import JsonResponse

def phone_number_eval(request):

    if phone_number is valid:
        response = {'status': 1, 'message': "Ok"}
    else:
        response = {'status': 2, 'message': "Please enter a valid phone number."} 

    return JsonResponse(response)

My Javascript isn't so good, but you can do something to the effect of if response.status is 2, display message. Maybe someone else can give the code for it.

Upvotes: 1

Related Questions