8

I'm using Symfony2 components and Doctrine. Validation works great on server side (constraints in Entities etc.) What I want is to validate form (my own custom built without using Symfony Form component) via AJAX.

Is there any way to use Validation component to validate fields using AJAX?

Or I should use jQuery validation plugin? Which seems not logical since then there will be 2 different validations used.

1 Answer 1

9

You can send the serialized form via AJAX and return the rendered form from the server side if it contains validation errors.

$.post($form.attr('action'), $form.serialize(), function (response) {
    if (response.success) {
        // do something on success
    } else {
        $form.replaceWith(response.form);
    }
});

On the server side you check if it's an AJAX request and return response in the JSON format.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the answer @elnur. This is also what I think but in this way I need to submit form to see errors. I want it more like jQuery Validate plugin when user starts typing for example email and if it's not correct - message is shown. But I don't want to make an AJAX request on each keypress.
Since it doesn't make sense to send a list of all registered emails to JS on the first page load — because of security and other issues — you'll have to make an AJAX request anyway. You just should do it not on each keypress, but after some timout or change event.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.