BumbleBee
BumbleBee

Reputation: 97

Jquery custom date validator works only once

I've faced an issue when tried to add custom validating method to jQuery.validator:

$.validator.addMethod("fromDate", function (value, element) {
    var fromDateTime = moment(value, 'm/dd/yyyy HH:mm');
    var toDateTime = moment($("#endDate").val(), 'm/dd/yyyy HH:mm');
    if (fromDateTime.isValid() && toDateTime.isValid()) {
        return toDateTime.diff(fromDateTime) > 0;
    }

    return false;
}, "Start datetime should be less than end datetime");

$('#queryingDateForm').on('submit', function (e) {
    e.preventDefault();
    $('#queryingDateForm').validate({
        rules: {
            start: {
                required: true,
                fromDate: true
            }
        },
        submitHandler: function (form) {
            load();
        }
    });
});

This line of code works correctly only first time, so validation works only once.

return toDateTime.diff(fromDateTime) > 0;

Second time and so on it returns the value which was returned first time.

Html:

<form id="queryingDateForm">
    <div class="input-group input-daterange">
        <input class="form-control dateTimePicker" id="startDate" type="datetime" placeholder="Date Start" name="start" required  />
        <span class="input-group-addon">@QueryingResources.To</span>
        <input class="form-control dateTimePicker" id="endDate" type="datetime" placeholder="Date End" name="end" required />

        <div class="input-group-btn">
        <button type="submit" class="btn btn-success searchQuery" id="searchDateBtn">@QueryingResources.Search</button>
        </div>
    </div>
</form>

and that is how the bootstrap datetimepicker is initialized:

$(".dateTimePicker").datetimepicker({
    autoclose: true,
    format: 'm/dd/yyyy hh:ii'
});

Thanks in advance

Upvotes: 3

Views: 704

Answers (1)

Sparky
Sparky

Reputation: 98718

The .validate() method is only use for initializing the plugin.

With your version below, the form is already in the process of being submitted before the validation plugin has even been initialized.

$('#queryingDateForm').on('submit', function (e) {
    e.preventDefault();
    $('#queryingDateForm').validate({ ....
  • How can validation take place after the submit event has been started?

  • How can validation take place without the plugin first being initialized?

You would never put the .validate() method inside of a submit event (or click event) handler.


The plugin already automatically captures the click and blocks the submit of the form. It simply gets called on page load within the DOM ready event handler...

$(document).ready(function () {

    $.validator.addMethod("fromDate", function (value, element) {
        // your function
        ....
    });

    $('#queryingDateForm').validate({ // initialize the plugin
        // your options
        ....
    });

});

Upvotes: 2

Related Questions