Need help with Date Validation script

nicolemccray
Tera Expert

I need an 'OnChange' script that will check to see whether the entered 'start_date' that is less than 2 weeks from today (or whatever day they are filling out the form).   If they enter a date less than 2 weeks away, I want to display a pop up message and prevent them from submitting the form.

1 ACCEPTED SOLUTION

chirag_bagdai
ServiceNow Employee
ServiceNow Employee

Hi Nicole,



If you don't want to do ajax calls each time, you can use JavaScript validation in onChange client script and onSubmit script :



var date1 = new Date(g_form.getValue('start_date');


var date2 = new Date();


var timeDiff = Math.abs(date2.getTime() - date1.getTime());


var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));


if(diffDays >= 14) {


      alert("Error Message");


      return false;


}


else


        return true;



Regards,


Chirag Bagdai


View solution in original post

34 REPLIES 34

I've copied and pasted Script Include and Client Script exactly As-Is, and still no message displays.


Interesting



Please try to debug the script by adding log or please check below conditions :



Getting new Date value   ?


Does Script include have client callable checked ?


What result are you getting while using GlideAjax ?


Here is the error I see when debugging:



find_real_file.png


Changing the Client Script fixed the issue:



function onChange(control, oldValue, newValue, isLoading, isTemplate) {
  if (isLoading || newValue === '') {
  return;
  }
  //onChange Client Script
  if(newValue != '') {
  var ga_date_validation = new GlideAjax('StartDateValidation');
  ga_date_validation.addParam('sysparm_name','validateDateStartDate');
  ga_date_validation.addParam('sysparm_start_date', newValue);
  ga_date_validation.getXML(startDateValidationResponse);
  }
}


function startDateValidationResponse(response) {

  var answer = response.responseXML.documentElement.getAttribute("answer");
  if(answer == "false") {
  g_form.setValue('start_date','');
  alert("You've entered a start date less than two weeks prior to the Start Date of the course. We cannot support all of the logistical requirements to ensure a successful delivery for this course.");
  }
}


Glad to know that the issue is fixed