The Now Platform® Washington DC release is live. Watch now!
01-14-2020 11:22 PM
I have a date field on incident form, i want to validate that that date I enter there should be after 7 days from today, How do I achieve this ?
Thanks!
Solved! Go to Solution.
05-10-2020 11:48 AM
Hi,
To validate date fields through client script, refer to this article
Kindly mark the comment as a correct answer and helpful if it helps to solve your problem.
Regards,
Asif
2020 ServiceNow Community MVP
01-14-2020 11:24 PM
Refer this article:
Please mark as Correct Answer and Helpful, if applicable.
Thank You!
Abhishek Gardade
01-14-2020 11:37 PM
Hi,
You can try below code:
function onChange(control, oldValue, newValue, isLoading, isTemplate) {
if (isLoading || newValue === '') {
return;
}
var date1 = new Date(g_form.getValue('date_field'));
var date2 = new Date();
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
if(diffDays != 7) {
alert("Error Message");
g_form.clearValue('date_field');
return false;
}
else
return true;
//Type appropriate comment here, and begin script below
}
Thanks,
Vishal Khandve
01-14-2020 11:38 PM
hi,
try this code will work irrespective of the date format:
Client Script:-
function onChange(control, oldValue, newValue, isLoading) {
if (isLoading || newValue == '') {
return;
}
//Type appropriate comment here, and begin script below
var start_date = g_form.getValue('start_date');
var ga = new GlideAjax("calcDate"); //name of script include
ga.addParam("sysparm_name", "getDate"); //name of function in script include
ga.addParam("sysparm_start", start_date); //send start value to script
ga.addParam("sysparm_end", newValue);
ga.getXML(checkDate); //callback function
}
Script Include :
function checkDate(response) {
var answer = response.responseXML.documentElement.getAttribute("answer"); //the response from the script
if (answer > 7) { //if the date received is more than 7 days from the start date
alert("End date cannot be later than 7 days after start date.");
g_form.setValue('end_date', ''); //remove value from end date field
return false;
}
}
script include code-
var calcDate = Class.create();
calcDate.prototype = Object.extendsObject(AbstractAjaxProcessor,{
getDate : function() {
var startDT = new GlideDate();
startDT.setDisplayValue(this.getParameter('sysparm_start'));
var endDT = new GlideDate();
endDT.setDisplayValue(this.getParameter('sysparm_end'));
var duration = new GlideDuration();
duration= GlideDate.subtract(startDT, endDT);
return duration.getDayPart();
},
type: 'calcDate'
});
Please mark as Correct Answer and Helpful, if applicable.
01-14-2020 11:42 PM
Try as well this code:-
var today = new Date();
var dateMS = today.getTime();
dateMS = dateMS + (7*24*60*60*1000);
var newDT = new Date();
newDT.setTime(dateMS);
g_form.setValue('ftr_needed_by',formatDate(newDT,g_user_date_format));