0

I am using jquery validation plugin and using this code, I try to fire some errors when fields do not meet required specifications

            $(document).on('click', '#btn_save', function() {
                $('form#new_inquiry').validate({
                    onkeyup: false,
                    errorClass: 'error',
                    validClass: 'valid',
                    highlight: function(element) {
                        $(element).closest('div').addClass("f_error");
                    },
                    unhighlight: function(element) {
                        $(element).closest('div').removeClass("f_error");
                    },
                    errorPlacement: function(error, element) {
                        $(element).closest('div').append(error);
                    },  
                    rules: {
                        pname: { required: true },
                        pid: { required: true, min: 1 },
                        country: { required: true },
                        cid: { required: true, min: 1 },
                        city: { required: true },
                        delivery_date: {
                            require_from_group: [1, '.delivery']
                        },
                        delivery_text: {
                            require_from_group: [1, '.delivery']
                        },                              
                        address: { required: true },
                        content: { required: true }
                    },
                    messages: {
                        pname: "You must enter a customer name before saving",
                        country: "You must select a valid country",
                        city: "Please fill in the city",
                        address: "Please fill in the address",
                        content: "Please fill in the order content"
                    },                              
                    invalidHandler: function(form, validator) {
                        $.sticky("Inquiry cannot be saved for the moment. </br>Please corect errors marked up", {autoclose : 5000, position: "top-right", type: "st-error" });
                    },
                    submitHandler: function(form) { 
                        $.ajax({
                            url: 'view/inquiry/inquiry_insert-exec.php',
                            type: 'post',
                            dataType: 'json',
                            data: $('form#new_inquiry').serialize(),
                            beforeSend: function() {
                                $('#amount').val($('#amount').val().toString().replace(/\,/g, '.'));
                                $('#btn_save').attr('disabled', true);
                                $('#btn_save').after('<span class="wait">&nbsp;<img src="<?= DIR_MEDIA;?>img/ajax_loader.gif" alt="" /></span>');
                            },  
                            complete: function() {
                                $('#btn_save').attr('disabled', false);
                                $('.wait').remove();
                            },                                  
                            success: function(json) {
                                if (json['status']) {
                                    if (json['id']) {
                                        location = '?route=home/inquiry/insert&id='+json['id']+"&tab=#tab2";
                                        //$('#myTab a[href="#tab2"]').tab('show');
                                    } else {
                                        location = '?route=home/inquiry'; 
                                    }
                                } else {
                                    $.sticky("There were errors while saving inquiry.</br>" + json['status'], {autoclose : 5000, position: "top-right", type: "st-error" });
                                }
                            }                           
                        });                          
                    }
                }); 
                if ($('#new_inquiry').valid()) {                    

                }
            }); 

But, this code is doing nothing.. I guess I am having a error somewhere but I do not understand where it could be I am using Firebug to track errors, but still no error fires after #btn_save is clicked The validate() is checked on the click of two buttons, and depending on the clicked one, the next event would be different, so the valid() function is used inside the click event, but still nothing happens. How can I see the errors, if any? I guess there are if the code does nothing

rosuandreimihai
  • 656
  • 3
  • 16
  • 39
  • 2
    You should call `.validate()` in your `$(document).ready()` function, not in a `click` handler. This method is used to initialize the plugin, it doesn't actually perform validation when you call it. The validation is performed automatically when you submit the form. – Barmar Jul 03 '14 at 18:41
  • the click handler is inside a $(document).ready() already, but the script is pretty large to put in here – rosuandreimihai Jul 03 '14 at 18:42
  • But you need to move this code OUTSIDE the click handler. See the examples in the documentation. – Barmar Jul 03 '14 at 18:43
  • ok, and if I move it outside the click handler, how can I test on click that the form is valid and only submit form after click? – rosuandreimihai Jul 03 '14 at 18:44
  • The validation plugin does that automatically for you when you submit the form. But if you need to test explicitly, you use `if ($("#new_inquiry").valid())`. – Barmar Jul 03 '14 at 18:46
  • Done that right now, and it didn'do anything. I moved the validate() outside the click handler and the tested inside the click with .valid() but still nothing – rosuandreimihai Jul 03 '14 at 18:48
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/56730/discussion-between-rosuandreimihai-and-barmar). – rosuandreimihai Jul 03 '14 at 18:49
  • You should have also shown the relevant HTML markup. See: http://stackoverflow.com/help/mcve – Sparky Jul 04 '14 at 04:31

1 Answers1

2

You dont need to add it inside click event. Here is the code.

$(document).ready(function() {
    $('#add_branch_form').validate({
        onkeyup: false,
        errorClass: 'error',
        validClass: 'valid',
        highlight: function(element) {
            $(element).closest('div').addClass("f_error");
        },
        unhighlight: function(element) {
            $(element).closest('div').removeClass("f_error");
        },
        errorPlacement: function(error, element) {
            $(element).closest('div').append(error);
        },
        rules: {
            pname: {required: true},
            pid: {required: true, min: 1},
            country: {required: true},
            cid: {required: true, min: 1},
            city: {required: true},
            delivery_date: {
                require_from_group: [1, '.delivery']
            },
            delivery_text: {
                require_from_group: [1, '.delivery']
            },
            address: {required: true},
            content: {required: true}
        },
        messages: {
            pname: "You must enter a customer name before saving",
            country: "You must select a valid country",
            city: "Please fill in the city",
            address: "Please fill in the address",
            content: "Please fill in the order content"
        },
        invalidHandler: function(form, validator) {
            $.sticky("Inquiry cannot be saved for the moment. </br>Please corect errors marked up", {autoclose: 5000, position: "top-right", type: "st-error"});
        },
        submitHandler: function(form) {
            if ($(form).valid()) {
                $.ajax({
                    url: 'view/inquiry/inquiry_insert-exec.php',
                    type: 'post',
                    dataType: 'json',
                    data: $('form#new_inquiry').serialize(),
                    beforeSend: function() {
                        $('#amount').val($('#amount').val().toString().replace(/\,/g, '.'));
                        $('#btn_save').attr('disabled', true);
                        $('#btn_save').after('<span class="wait">&nbsp;<img src="<?= DIR_MEDIA;?>img/ajax_loader.gif" alt="" /></span>');
                    },
                    complete: function() {
                        $('#btn_save').attr('disabled', false);
                        $('.wait').remove();
                    },
                    success: function(json) {
                        if (json['status']) {
                            if (json['id']) {
                                location = '?route=home/inquiry/insert&id=' + json['id'] + "&tab=#tab2";
                                //$('#myTab a[href="#tab2"]').tab('show');
                            } else {
                                location = '?route=home/inquiry';
                            }
                        } else {
                            $.sticky("There were errors while saving inquiry.</br>" + json['status'], {autoclose: 5000, position: "top-right", type: "st-error"});
                        }
                    }
                });
            }
        }
    });
});
Muhammad Saud
  • 356
  • 3
  • 13
  • Sorry, but that is not helpful.. I need the form to be validated upon click event, and depending on the clicked button, the validate is followed by another action – rosuandreimihai Jul 03 '14 at 19:02
  • buddy, you did't mentioned that in your question. – Muhammad Saud Jul 03 '14 at 19:04
  • please addd the markup and the JS script in jsfiddle – Muhammad Saud Jul 03 '14 at 19:06
  • it's a huge code, with dependencies and cannot be uploaded – rosuandreimihai Jul 03 '14 at 19:06
  • then update the question and make it clear, what exactly you want to do? – Muhammad Saud Jul 03 '14 at 19:32
  • @rosuandreimihai, if you want help, you're expected to be able to accurately describe the problem and construct a concise demo of the issue. See: http://stackoverflow.com/help/mcve – Sparky Jul 04 '14 at 04:45
  • @Muhammad Saud: the code provided by you does not differ from the code suggested by Barmar, so why is it in a Answer? Also, this code has one error specified in the documentation of jquery validation plugin. It's wrong to say {if ($(form).valid())}. Actually, you must use the correct aproach {if (form.valid())} – rosuandreimihai Jul 04 '14 at 04:54