Need help with date validation servicenow

Hemamani Prabha
Tera Contributor

Requirement is to Add a mandatory date field 'Retirement date' with date logic cannot be <= today or >6M
Here's my code below:

Script include:

var ClientDateTimeUtils = Class.create();

ClientDateTimeUtils.prototype = Object.extendsObject(AbstractAjaxProcessor, {
getDateDiff: function() {
var firstDT = this.getParameter('sysparm_fdt'); //Exception Date by user
var diffTYPE = this.getParameter('sysparm_difftype'); // Date-Time Type to return the answer as. Can be second, minute, hour, day
var diff = gs.dateDiff(gs.nowDateTime(), firstDT, true);
if ((diff <= 0) || (diff > 15811200)) {
return "failure";
} else {
return "Success";
}
}


OnChange catalog client script:

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

//Type appropriate comment here, and begin script below
if (oldValue != newValue) {
var cdt = g_form.getValue('Retirement_date'); //First Date/Time field
var dttype = 'second'; //this can be day, hour, minute, second. By default it will return seconds.

var ajax = new GlideAjax('ClientDateTimeUtils');
ajax.addParam('sysparm_name', 'getDateDiff');
ajax.addParam('sysparm_fdt', cdt);
ajax.addParam('sysparm_difftype', dttype);
ajax.getXML(doSomething);
}

function doSomething(response) {
var answer = response.responseXML.documentElement.getAttribute("answer");
if (answer == "Failure" && cdt != '') //Ifanswer checking from script include
{
g_form.addInfoMessage("Please enter a valid date"); //Error Message
g_form.setValue('Retirement_date', '');
return false;
}
}
}

This is not working. Please let me know where am I going wrong. I'm not even getting any error message. I'm able to select any date and submit the request which shouldn't happen. Please help!!

1 REPLY 1

Siddhesh Wani1
Tera Guru

To compare two dates you have to convert the dates in same format 

Code for the script include to check the dates 

 

Script Include:

getDate: function() {

        var retirementDate = this.getParameter("sysparm_fdt");
        var retirementDateGDT = new GlideDateTime(retirementDate);

        var afterdate = new GlideDateTime();
        afterdate.addMonths(6);
     
        var comparision = retirementDateGDT.compareTo(afterdate);
     
      After compare this two you will get the ans in the following format. 
      //0 = Dates are equal
     //1 = The object's date is after the date specified in the parameter
    //-1 = The object's date is before the date specified in the parameter

        if (comparision == -1) {
            return "failure";
           } else {
                return "Success";
          }
    },