need catalog variable date to validate it is in future

karendk
Kilo Explorer

I've seen this in the community where this is working for others, but it's not working for me.   What do I have wrong?   I get no error message.   It's just ignored.

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

if(newValue != '')
{
var reqDate = new Date(getDateFromFormat(newValue, g_user_date_format));
var today = new Date();

if(reqDate.getTime() <= today.getTime()) {

alert('Date must not be in the past.');
  g_form.setValue('sDate', '');
}
}
}

1 ACCEPTED SOLUTION

Tanaji Patil
Tera Guru

Hi Karen,



You are just comparing the time. You should first compare date and then time. Or both at the same time.


Try with the below shown code-



function onChange(control, oldValue, newValue, isLoading, isTemplate) {


  if (isLoading || newValue == '') {


  return;


  }



// if(newValue != '') don't need this as you already have checked above


// {


  var reqDate = new Date(newValue);


  var today = new Date();


  if(reqDate <= today){


  alert('Date must not be in the past.');


  g_form.setValue('closed_at', '');


  }


// }


}



Thanks,


Tanaji


View solution in original post

16 REPLIES 16

Pradeep Sharma
ServiceNow Employee
ServiceNow Employee

Hi Karen,



The above script will work if the variable is of type date. I'm assuming that you have created a variable of type date/time. If yes below script will work.


function onChange(control, oldValue, newValue, isLoading){



  if (isLoading || newValue == '') {


  return;


  }



  if(newValue != '')


  {


  var reqDate = new Date(getDateFromFormat(newValue, g_user_date_time_format));


  var today = new Date();


  alert(reqDate.getTime());


  alert(today.getTime());



  if(reqDate.getTime() <= today.getTime()) {


  alert('The loan required from date cannot be in the past');


  g_form.setValue('sDate',''); //Assuming sDate is the name of the catlog variable created.


  }


  }


}



Please let me know the outcome.


sDate is the catalog variable I'm using and it's a date type



I replaced my previous code with your code shown above, but it's still not working.   I can use the calendar tool to pick a date in the past or future and it still doesn't pop the alert.   It's like the script isn't firing.   I've confirmed it's active.   I can see the alert statements in the code, but I'm not seeing any alerts when use Try It on the Catalog Item and pick dates for this field.   I must be overlooking the obvious...


Make sure that you are selecting sDate in the variable name field on the client script.


Hi Karen,



Can you paste the screenshot of the variable you have created so that I can take a look and help you out.