I have two date fields, CommenceDate and EndDate, and I’m trying to write a JavaScript code to validate the EndDate field so that the date selected for that field can never be more than 1100 days after the date selected for CommenceDate.
I want the EndDate field to throw an error message when you try to enter a date that’s more than 1100 days from the date in CommenceDate and for the CommenceDate field to throw an error if the date in that field is changed to a date that will make the date in EndDate field more than 1100 days.
I’m doing this for a public webform and trying to use moment.js but my code isn’t working.
Please assist.
Hello @JayAnaman,
Welcome to Plumsail Community!
You can use the code below to calculate the number of days between two dates and throw the error if the interval is not valid.
fd.rendered(function() {
$.getScript('https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment-with-locales.min.js')
.then(function() {
fd.field('Date2').validators.push({
name: 'Check Date',
error: "Date is invalid",
validate: function(value) {
if(fd.field('Date1').value) {
var date1 = moment(fd.field('Date1').value);
var date2 = moment(fd.field('Date2').value);
var dateDiff = date2.diff(date1, 'days', false);
if(dateDiff > 3){
return false;
}
return true;
}
return false;
}
});
});
});
Don't forget to replace Date1 and Date2 with the internal field names.
Thank you, Margarita, the code works although I had to change "validators.push" to .addValidator to get it to work. Do you have any idea why that is?
Thank you again.
Hello @JayAnaman,
Both methods should work.
What designer are you using? The desktop or the web designer?
Did you get errors in the browser console(F12) when using the validators.push
method?