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

Ankur Bawiskar
Tera Patron
Tera Patron

@fgh1 

update as 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(g_form.getValue('end_date')).getTime();
		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

Hello @Ankur Bawiskar 

 

I have tried your code but it is restricting future time as well as past time for todays date 

I have added logs to debug I am getting End time lesser than Rightnow time  whether I am selecting past time or future time for todays date so it is restricting future time as well as past time for todays date .

@fgh1 

what came in alert for both the values for time?

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

@Ankur Bawiskar

 

RightNow - 1698313784368
end            - 1698272370000 

 

These are the alerts when I am giving 3 hrs future time for todays date