Can you help me in creating custom validation for SharePoint online form on a Start date and End Date that if the end is greater than 1 year of the start date, an error is displayed stating it cannot be greater than 1 year.
Thanks
Hello @flowy,
You need to calculate the difference between two dates and add either the form or field validation.
This is the code for a from validation:
// load external library
requirejs.config({
paths: {
luxon: 'https://cdn.jsdelivr.net/npm/luxon@3.5.0/build/global/luxon.min'
}
});
fd.spRendered(() => {
require(['luxon'], () => {
// add new form Validator
fd.validators.push({
name: 'MyCustomValidator',
error: 'more then 1 year',
validate: value => {
let start = fd.field('StarDtae').value;
let end = fd.field('EndDate').value;
if (start && end) {
let startDate = luxon.DateTime.fromISO(start.toISOString());
let endDate = luxon.DateTime.fromISO(end.toISOString());
// calculate the difference between two dates
let dateDiff = endDate.diff(startDate, 'years').as('years');
if (dateDiff > 1) return false;
return true;
}
}
});
});
});
For field validation instructions please see Validate fields article.
Also see the Date and Time: calculate difference, adjust values
This is great! Thanks for your help as always. Could you also kindly advise on if I wanted to set the start date to the current date and time?
Thanks again!
You can use this code:
fd.field('StarDtae').value = new Date();
Please learn more on how to handle Date and Time field with JavaScript in the documentation: