Validation for start date not working as expected

Jaya9
Tera Contributor

Hi ,

I have a record producer and have field as start date of Type date . I wanted to add a validation as we cannot select past date . It should only allow to select present date and future dates . 

I have written below catalog client script for it :

function onChange(control, oldValue, newValue, isLoading) {
   if (isLoading || newValue == '') {
      return;
   }
   var date1= g_form.getValue('license_start_date');
   var today_date = new Date();
   var today_date_time = formatDate(today_date, g_user_date_time_format);
   g_form.addInfoMessage(today_date_time);
 
   if(date1< today_date_time ){
    g_form.addErrorMessage("license date should  not be before today's date");
    g_form.clearValue('license_start_date');
 
   }
}
This script is not allowing to select previous dates (working fine) but i m not able to select current date as well with this script .. can someone please help me resolve this . 
2 REPLIES 2

rajeev17
Mega Guru

Hi Jaya ,

 

i have corrected the code with some changes please try the below:

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


var selectedDate = new Date(g_form.getValue('license_start_date'));


var today = new Date();
today.setHours(0, 0, 0, 0);


if (selectedDate < today) {
g_form.addErrorMessage("License start date cannot be in the past.");
g_form.clearValue('license_start_date');
}
}

Viraj Hudlikar
Tera Sage
Tera Sage

Hello @Jaya9 

In your code you are comparing input as date and comparing with datetime so it's not working as expected.

Also, when script is not working do try to put alert statement for logging so you know what is happening.

 

Also, this part can be easily achieved through ui policy without writing any script as ServiceNow is more of nocode lowcode.

Refer this best article which will help you https://www.servicenow.com/community/developer-articles/no-code-date-validations-through-catalog-ui-...

 

If my response has helped you hit helpful button and if your concern is solved do mark my response as correct.

 

Thanks & Regards
Viraj Hudlikar.