简体   繁体   中英

parsley.js - custom validation for date field

I have been reading the parsley.js docs and I have tried to write a custom validator to validate if a date is greater than todays date.

I have the conditional code written, but I am completly confused about how to apply the conditional error message.

I have completed the task with a parsley maxlength validator, but realise that this is less than perfect.

How do I write the custom validation with parsley?

Here is my js/jq code that dynamically adds & deletes the validation using the maxlength:

if(formattedStartDate > todaysDate) {

    $('#id_voluntary_start_date').attr('data-parsley-maxlength', '1');
    $('#id_voluntary_start_date').attr('data-parsley-maxlength-message', '{% trans "Commencement Date must not be greater than today." %}');
    $('#id_voluntary_start_date').parsley();
} else {
    $('#id_voluntary_start_date').attr('data-parsley-maxlength', '50');
}

Any help with implementing the custom validation would be appreciated.

First of all set one hidden textbox and store today's date in it and just write below code on date field you want to check.

data-parsley-dlte = "#hiddentextboxid",
data-parsley-dlte_message = "Your custom message"

Don't forget to set parsley on the form in which you have your dom elements.

If this doesn't work check the version of parsley js .

Hope this is helpful.

All you need to do is register your custom validator either globally (in window.ParsleyConfig) or for your particular form as follows:

  myForm.parsley({
    validators: {
        custom: function (value) {
            var now = new Date();
            var date = new Date(value);
            return date < now;
        }
    },
    messages: {
        custom: 'Commencement Date must not be greater than today'
    }
});

Here is jsFiddle with a sample

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM