Moji
Moji

Reputation: 1830

JQuery validator does not validate the form unless the input is filled with required values and is sent once

I am trying to validate my form before sending it using JQuery validator but the problem is that the form does not get validated unless I press submit once(with the required length) and then it begins validating. It does not validate even if I hit submit without filling the input with the minimum length, it does not validate either. here is my html:

 <form class="newRegister-formBox basketForm" id="confirmPhoneNumberForm" autocomplete="off">
                    <input autocomplete="off" type="text" name="code" id="code" class="form-control persianDigitInput" placeholder="">    
                <div class="newRegister-button">
                    <button type="button" id="send-confirm-phone-number-code" class="animateBtn greenAnimateBtn" >
                        <i class="fa fa-check"></i>
                        confirm
                    </button>
                </div>
    </form>

here is my JS code and I am using Backbone JS. I have defined the onclick event of the button to cal this function:

   sendConfirmPhoneNumberCode: function() {

        var self = this;
        var $form = $("#confirmPhoneNumberForm");

        $("<input />").attr("type", "hidden")
            .attr("name", "PhoneNumber")
            .attr("value", $("input[name='PhoneNumber']").val())
            .appendTo($form);

          $("#confirmPhoneNumberForm").validate({
            rules: {
                code: {
                    required: true,
                    minlength: 4
                }
            },
            messages: {
                code: {
                    required: $utils.messages.user.required_ConfirmPhoneNumberCode,
                    minlength: $utils.messages.user.minlength_ConfirmPhoneNumberCode
                }
            }
        });

Upvotes: 0

Views: 46

Answers (1)

wizzwizz4
wizzwizz4

Reputation: 6426

$("#confirmPhoneNumberForm").validate turns on validation when you call it. Instead of calling it in the click event handler, call it at the beginning.

Upvotes: 1

Related Questions