I have a field called 'StartDate'. I want an error message that says "invalid date" if the date entered on 'Start Date' is less than two days from todays (current) date. How do I do this in javascript? I tried using moments but could not make it work. I maybe doing it wrong.
Hello @Jamail_Serio,
You can add custom validator to the field and calculate difference between two dates using moment.js library like this:
requirejs.config({
paths: {
moment: "https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment-with-locales.min"
}
});
fd.spRendered(function() {
require(['moment'], function(moment) {
fd.field('StartDate').validators.push({
name: 'Date',
error: 'Error message',
validate: function(value) {
var today = moment(new Date());
var selectedDate = moment(value);
var dif = today.diff(selectedDate, 'days', false)
if (dif > 2) {
return false;
}
return true;
}
});
})
});
Hi,
Can this validator be amended so that the error message displays if the date entered is less than todays date?
Hello @flowy,
You can change it like so:
require(['moment'], function(moment) {
fd.field('Date').validators.push({
name: 'Date',
error: 'Error message',
validate: function(value) {
var today = moment(new Date());
var selectedDate = moment(value);
var dif = today.diff(selectedDate, 'days')
if(dif > 0) {
return false;
}
return true;
}
});
})
You can also set the minimum allowed date using the code:
fd.field('Date').widgetOptions = {
min: new Date()
}
Thank you, The moment link above is no longer a functional link.
The link works for me:
https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment-with-locales.min.js