End date should be always greater than start date

srinivas snow22
Kilo Explorer

Date Validation

End date should be always greater than start date. How to write client side validation or server side validation

Please could you help me on this?

5 REPLIES 5

Nikita30
Mega Sage

Hi Srinivas,

 

Please check the below link hope it helps or you can try the below code

 

https://community.servicenow.com/community?id=community_question&sys_id=3fad2cabdb402384a39a0b55ca96192b

 

Create an onChange script for your start_date and end_date fields.

//start_date onChange Function
function onChange(control, oldValue, newValue, isLoading) {
if (isLoading || newValue == '') {
return;
}

//Type appropriate comment here, and begin script below
var nowDate = new Date(); //Creates a JS date object for right now
var checkStart = new Date(newValue); // Create a JS Date object using the desired start_date field (from newValue parameter)

if (nowDate >= checkStart){ //JS Date objects compared
alert('You cannot select today or a day in the past');
g_form.setValue('start_date','');
}
}

 

//end_date onChange Function
function onChange(control, oldValue, newValue, isLoading) {
if (isLoading || newValue == '') {
return;
}

//Type appropriate comment here, and begin script below
var startDate = new Date(g_form.getValue('start_date')); //get the value of the start_date field using the g_form.getValue method
var checkEnd = new Date(newValue); // create a new JS date from the desired end_date field (using newValue parameter)

if (checkEnd <= startDate){ //Again - a simple JS Date object comparison
alert('End date must be after start date');
g_form.setValue('end_date','');
}
}

Please mark the response as Helpful/Correct, if applicable. Thanks!

 

 

 

Working fine without any errors

Thank you

Ankur Bawiskar
Tera Patron
Tera Patron

Hi,

you can use onSubmit client script

function onSubmit() {
	//Type appropriate comment here, and begin script below

	g_form.hideErrorBox('start_date');
	g_form.hideErrorBox('end_date');

	if(g_form.getValue('start_date') != '' && g_form.getValue('end_date')){
		var start = new Date(g_form.getValue('start_date')).getTime();
		var end = new Date(g_form.getValue('end_date')).getTime();
		if(end < start){
			var message = 'Please give valid start and end dates';
			g_form.showErrorBox('start_date', message);
			g_form.showErrorBox('end_date', message);
			return false;
		}
	}
}

Regards
Ankur

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader

How we can write same validation in script include and client script