Search code examples
jquerybootstrap-datepickercustomvalidator

jQuery validator using previous value after bootstrap datepicker


I'm using a bootstrap datepicker that is initialised like so...

$(".datepicker").datepicker({
    language: "en-GB",
    startDate: "01/01/1900",
    endDate: "31/12/2200",
    autoclose: true,
    forceParse: false
});

Then I have a custom jQuery validator which is...

$(function () {
    $.validator.addMethod("futuredaterequired", function (value, element, params) {
        //Validation code here
    });
});

However, once I've make a selection from the datepicker the value in the validator method is the previous value that was selected in the datepicker. Not the newly selected value.

So I tried using element to get the value again, however that also returns the previous value of the datepicker. If I put a setTimeOut on the entire method then the value is correct, However the timeout causes other issues.

Any thoughts on how I could fix this?


Solution

  • The only solution to this I have now found is...

    $(".datepicker").datepicker({
        language: "en-GB",
        startDate: "01/01/1900",
        endDate: "31/12/2200",
        autoclose: true,
        forceParse: false
    })
    .on('changeDate', function(e) {
        $(this).valid();
    });
    

    This way, the jQuery validation is run after the actual value has been changed in the input.

    The method still runs on the initial selection of a date and still uses the previous date value. However when it runs a 2nd time on changeDate it uses the correct value.

    Not ideal... but it works. If you have any better solutions, please let me know.