Restricting past date and time in date/time field using onChange client script

fgh1
Tera Contributor

Restricting past date and time in date/time field using on change client script as below, but it is restricting only old date IF I am selecting past time of todays date it is not restricting, it so it should restrict past time too

 

my onChange client script for DateTime field -

 

function onChange(control, oldValue, newValue, isLoading, isTemplate) {
    if (isLoading || newValue === '') {
        return;
    }
    var EventDateTime = newValue;
    var newdt = new Date(EventDateTime);
    var EventDate = formatDate(newdt, 'yyyyMMdd');
    var RightNow = new Date();
    var RightNowDate = formatDate(RightNow, 'yyyyMMdd');
    if (EventDate < RightNowDate) {
        g_form.clearValue('end_date');
        g_form.showFieldMsg('end_date', 'Planned end date must be after the current date', 'error', true);    }}

 

@Ankur Bawiskar please assist 

9 REPLIES 9

@fgh1 

why are you selecting today's date?

share your form screenshots.

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

datetime_360.jpg

 

@Ankur Bawiskar  User must can select future time also even it is for todays date that is the customer requirement 

@fgh1 

try this

function onChange(control, oldValue, newValue, isLoading, isTemplate) {
	if (isLoading || newValue === '') {
		return;
	}
	g_form.hideErrorBox('end_date');
	if (newValue != oldValue) {
		var RightNow = new Date().getTime();
		var end = new Date(getDateFromFormat(g_form.getValue('end_date'), g_user_date_time_format));
		if (end <= RightNow) {
			g_form.clearValue('end_date');
			g_form.showFieldMsg('end_date', 'Planned end date must be after the current date', 'error', true);
		}
	}
}

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

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

Anurag Tripathi
Mega Patron
Mega Patron

Hi,

Why don't you use a No Code Solution like below using conditions on UI policy

AnuragTripathi_1-1698316232232.png

 

In the Run script you can throw an error or info message and return false

 

More Eg here ->No Code date validations through (Catalog) UI Poli... - ServiceNow Community

 

 

 

-Anurag

Community Alums
Not applicable

Hello @fgh1 ,

 

You can use the UI policy for date validations.

 

Refer to this article by  @Mark Roethof.

 

Thanks

Anand