How to compare previous value and current value of date field?

abhi710
Tera Contributor

Hi All,

I have a requirement stating that, In my form there is date/time field. I need to write a client script on that field. Whenever i select the date before last 6 months of previous value it should throw me an error/warning like "Date cannot be before last 6 months" & for future date it should throw me an error like "Date cannot be in future". I need to validate from value in date field. For example date field has 2/4/2020, this field can update only up to past 6 months(i.e. till oct/2019) and do not update to future date.

 

How can we achieve this by using client scripts?

Thank you all in advance.

7 REPLIES 7

Priyanka0402
Mega Sage
Mega Sage

Hello @abhi710 

Please use the below OnChange code:

function onChange(control, oldValue, newValue, isLoading, isTemplate) {
if (!isLoading && newValue) {
var currentDate = new Date(newValue);
var previousDate = new Date(oldValue);
var sixMonthsAgo = new Date();
sixMonthsAgo.setMonth(sixMonthsAgo.getMonth() - 6);

if (currentDate < sixMonthsAgo) {
alert("Date cannot be before last 6 months");
g_form.clearValue('u_a_date');
return false;
}

if (currentDate > new Date()) {
alert("Date cannot be in future");
g_form.clearValue('u_a_date');
return false;
}
}
}

If my response helped please mark it correct and close the thread so that it benefits future readers.

Regards

Priyanka

Nayan  Dhamane
Kilo Sage
Kilo Sage

Hello @abhi710 ,

Please create 2 UI policy as below:

 

1. Ui policy with condition the selected date is more than 6 months, Use the below script in run script of UI Policy:

function onCondition() {
alert("Date cannot be before last 6 months");
var start = g_form.clearValue('datefield');
}

 

2.Ui policy with condition the selected date is not past date, Use the below script in run script of UI Policy:

function onCondition() {
alert("date cannot be past date");
g_form.clearValue('datefield');
}

If my answer solved your issue, please mark my answer as āœ…Correct & ļ‘Helpful based on the Impact

Best Regards,
Nayan Dhamane
ServiceNow Community Rising Star 2023.

Hello @abhi710 ,

Please check if given method is working?

 

If my answer solved your issue, please mark my answer as āœ…Correct & ļ‘Helpful based on the Impact

Best Regards,
Nayan Dhamane
ServiceNow Community Rising Star 2023.

Hi @Nayan Dhamane ,

Ui policy is taking the current date. I need to take the store value from field and compare with the entered date and show the error message if it is before 6 months/ future date otherwise update.

Regards,

Abhi