Date field Validation to restrict selecting past dates

Rocky5
Kilo Sage

Hi Experts,

I have written a onchange catalog client script on the "Start Date" variable to restrict users from not to select the past dates. The below is the code I am using, But the code is also triggering if the selected date is today's date (current date). All I need to is restrict user to not to select any date before current date. 

code: 

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

//Type //get the entered date string
var enteredDate= g_form.getValue('start_date');
//get the current date/time
var rightNow = new Date().valueOf();
var dateToCheck = new Date(enteredDate).valueOf();
if (dateToCheck < rightNow)
{
//Display Error Message
g_form.addErrorMessage(getMessage('Select appropriate date'));
g_form.setValue('start_date','');
}
}

Any ideas on how to achieve this ? 

 

Thanks in advance,

Rocky.

10 REPLIES 10

Mark Roethof
Tera Patron
Tera Patron

Hi there,

Have you considered using a (Catalog) UI Policy to achieve date validations? There's almost no-code needed to achieve date validations this way. Have a look at an article I wrote on this:
No Code date validations thru (Catalog) UI Policies

If my answer helped you in any way, please then mark it as helpful.

Kind regards,
Mark
2020 ServiceNow Community MVP
2020 ServiceNow Developer MVP

---

LinkedIn
Community article list

 

Kind regards,

 

Mark Roethof

Independent ServiceNow Consultant

10x ServiceNow MVP

---

 

~444 Articles, Blogs, Videos, Podcasts, Share projects - Experiences from the field

LinkedIn

Hi Mark,

I have already tried this way, But it did not work on service portal. The script triggered for whatever date is selected (even for today and tomorrow's date), But it worked on non-service portal view i.e. when we click "Try it" on the catalog item. 

Any idea on why it is not working on service portal. 

 

Thanks,

Rocky.

Should be able to work. For simple validations also for data and date/time. For complex validations, only for date.

Did you select Run Scripts in UI Type "All"?

Can you share what you've setup that did not work? Also look at the example in the article, all working examples for Platform UI and Service Portal.

If my answer helped you in any way, please then mark it as helpful.

Kind regards,
Mark
2020 ServiceNow Community MVP
2020 ServiceNow Developer MVP

---

LinkedIn
Community article list

 

Kind regards,

 

Mark Roethof

Independent ServiceNow Consultant

10x ServiceNow MVP

---

 

~444 Articles, Blogs, Videos, Podcasts, Share projects - Experiences from the field

LinkedIn

Yes, The UI type is "All". Below are screenshots.

find_real_file.png

 

find_real_file.png

 

Thanks,

Rocky.