views:

29

answers:

1

I have a mixed client-side/server-side validation using jQuery validation plugin. The validation happens on both submit and for some fields on change. The form is being submitted via AJAX. There is another validation going on the application just before updating the DB. If the data changes are not stored to the database due to this validation failing I'm returning the result via JSON to the JS method handling the AJAX form submission. Ideally I would raise an error with custom message passed from the backend to JS by something like $.validator.showErrors(obj); as discussed here Unfortunately the validator.showErrors(...) method is not defined in that context:

$(document).ready(function() {
    $('.form').each(function() {
    $(this).submit(function(e) {
        e.preventDefault();
        if ($.submitForm()) {
    (...)
            $.post(url, $.param(context), function(data) {
                if (!data.success) {
                    $.validator.showErrors(...);
                    //$("#basicdetails").validate();
                }
            }, "json");
        }
        (...)

You can also see that I've tried form revalidation which should also trigger appropriate error (although more of an hack that the real solution).

I would like to retain static client-side validation and after ajax submission to be able to raise any errors that might have occurred on the backend.

Thank you for any help you can provide.

Pawel

+3  A: 

.validate() is for setting up validation, to trigger it you should use .valid() like this:

$("#basicdetails").valid();
Nick Craver
Thank you that does it. But it is my fallback option. Ideally after submitting the form I would just trigger displaying of custom message for the relevant field (for the field being part of the validation on submission).
Pawel
@Pawel - Can you elaborate a bit more? If your server response contained specific messages, in JSON for example you could display those...is that what you're after?
Nick Craver
Yes please. That's exactly what I'm after.
Pawel
@Pawel - If you're not calling `.validate()` previously, use `$("#basicdetails").validate().showErrors(data);` else, when you create the validator, e.g. `var validator = $("#basicdetails").validate()` then in your success handler: `validator.showErrors(data);`.
Nick Craver
Works perfect. Thank you Nick Craver! :)
Pawel
@Pawel - Welcome, be sure to accept answers on this and future questions! :)
Nick Craver
Sorry didn't notice. It won't happen again :)
Pawel
Is it possible to valid the content of a <div> and not use a <form> ?
Kris-I
@Kris-I - It is not, the plugin is specifically for `<form>` elements, it's actually using the `form.elements` DOM property to loop though controls, and `element.form` to get back to the `<form>`, etc.
Nick Craver