Pranaya Behera
Pranaya Behera

Reputation: 555

Form validation while the submit button is triggered via javascript

I have a form that opens in the modal. I want to implement validation for that . However, I tried to implement the jQuery form validation but in vain. The main reason of being not able to trigger the form validation is that the form submit button is triggered using javascript. While the form submits it doesn't execute the validation part.

What is the work around for this ?

here is the form ::

<div id="__paymentModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
        <h3 id="myModalLabel">Make Payment Request</h3>
    </div>
    <div class="modal-body">        
        <form method="post" action="" id="__paymentForm" class="form-horizontal">
            <input type="text" name="name" value="" placeholder="Payee Name">
            <input type="text" name="phone" value="" placeholder="Phone"/>
            <input type="text" name="address" value="" placeholder="Address"/>
            <input type="text" name="pincode" value="" placeholder="Pincode" />
            <input type="text" name="amount" value="" placeholder="Amount"/>
        </form>
    </div>
    <div class="modal-footer">
        <button class="btn" data-dismiss="modal" aria-hidden="true" onclick="javascript: reset()">Close</button>
        <button class="btn btn-primary" onclick="javascript: sendPaymentRequest()">Save changes</button>
    </div>
</div>

And the JavaScript that triggers the form submission.

var paymentReqBttnObject = undefined;

function reset() {
    window.paymentReqBttnObject = undefined;
}

function openModalForPaymentReq(ele) {
    $('#__paymentForm input[type="text"]').val("");
    $('#__paymentModal').modal( { backdrop: false });
    window.paymentReqBttnObject = ele;
}

function sendPaymentRequest() {
    $.ajax({
        type: "post",
        url: url,
        data: $('#__paymentForm').serialize(),
        processData : true,
        dataType: 'html',
        beforeSend: function() {
                $('#__paymentModal').hide();
        },
        success: function(data, textStatus, xhr) {
                var json = $.parseJSON(data);
                if(json.success == "request_made") {
                    $(paymentReqBttnObject).addClass("btn-requested").html("Payment Requested");
                    $(paymentReqBttnObject).unbind("click");
                } else {

                }
                window.reset();
        },
        error: function(xhr, textStatus, errorThrown) {
            window.reset();

        }
    });
}

I also tried jquery form validator but still not showing any errors while submitting the form. It straight away goes to the database where only null values are updated.

Validation jQuery

$(document).ready(function(){
    $("#__paymentForm").validate({
            rules: {
                phone: {           //input name: fullName
                    required: true,   //required boolean: true/false
                    minlength: 10,
                    maxlength: 10       
                },
                address: {
                        required: true
                },
                pincode: {
                        required: true,
                        minlength: 6,
                        maxlength: 6
                }
                amount: {
                        required: true
                }
            },
            messages: {               //messages to appear on error
                phone: {           //input name: fullName
                    required: "Your Phone Number",   //required boolean: true/false
                    minlength: "Correct contact number.",
                    maxlength: "Correct contact number."
                },
                address: {
                        required: "Where to collect money."
                },
                pincode: {
                        required: "Pincode is required to locate the city and all others.",
                        minlength: "Correct Pincode Please.",
                        maxlength: "Correect Pincode Please"
                }
                amount: {
                        required: "What is the amount."
                },
            },
            submitHandler: function(form) {
                   $(form).ajaxSubmit({
                        success: function(){
                            alert('inside');
                      }
                    });
            }

        });  
})

Upvotes: 0

Views: 2171

Answers (2)

Joe
Joe

Reputation: 15558

You had a few things wrong with your code:

  • Missing , after the pincode validation rules. This appeared twice.
  • Inline events (onClick). jQuery makes it really easy to attach events. In my code I replaced your inline event on the 'close' button with:

    $('.modal-footer .btn').on('click', function(){ reset(); });
    

    This is easier to read and nicely separates the HTML from your javascript. Read more about .on() in the documentation.

  • The validation plugin is triggered when the form is submitted. Your original code used an ajax request in a separate event handler so the plugin was never called. You also had your submit button ("save changes") outside the <form> tags which is another reason it wouldn't work.

I moved your buttons inside the form and fixed/improved the other areas of your javascript so it now works: http://jsfiddle.net/U2hHH/4/ - currently the formatting isn't great but it's validating the form correctly.

I've combined your ajax functions into just one in the submitHandler: callback. The ajax should work but I can't guarantee it so if it doesn't work please check your browser's console.

Upvotes: 3

Precastic
Precastic

Reputation: 4021

You must return false; to stop the default functionality of the click event from happening, like this:

function sendPaymentRequest() {
  $.ajax({
    ....
  });
  return false; // return false here
}

and change your onclick:

onclick="javascript: return sendPaymentRequest()"

or you could just do this:

onclick="javascript: sendPaymentRequest(); return false;"

Upvotes: -1

Related Questions