Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

Validate Date in Client Script

CharlesR1
Kilo Guru

Hello All,

Hopefully a quick one - I'm having trouble getting a Client Script to work properly - I have a date field 'ends' (type is 'Date'), which we need to ensure is in the future.

I am using the following Client Script and Script include, but I receive an onChange script error. Any suggestions would be greatly appreciated.

Thanks,

Charles

Client Script:

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

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

          return;

    }

      // assuming datefield is a string

      var ajax = new GlideAjax('CheckDateAjax');

      ajax.addParam('sysparm_name','compareDateToNow');

      ajax.addParam('sysparm_datefield', ends);

      ajax.getXML(SetValues);

               

      function SetValues(response) {

          var answer = response.responseXML.documentElement.getAttribute("answer") * 1;

              if(answer > 0){

                      g_form.showFieldMsg('Please ensure that the Expiry date is in the future!','error');

return false;

              }

     

      }

 

}

Script Include:

      var CheckDateAjax = Class.create();

      CheckDateAjax.prototype = Object.extendsObject(AbstractAjaxProcessor, {

              compareDateToNow: function () {

              var date1 = new GlideDateTime();

              var date2 = new GlideDateTime();

              date2.setDisplayValue(this.getParameter('sysparm_datefield'));

                      return date1.compareTo(date2);

              }

      });

1 ACCEPTED SOLUTION

andrew_venables
ServiceNow Employee
ServiceNow Employee

No need to use the server one for this, try this in your client script:



g_user_date_format is a global variable that gives you the user's date format


and formatDate and getDateFromFormat are two useful functions for working with dates on the client



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


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


          return;


    }


  //current date  


  var currentDateObj = new Date();  


  var currentDateStr = formatDate(currentDateObj, g_user_date_format);  


  var currentDateNum = getDateFromFormat(currentDateStr, g_user_date_format);  


 


  var startDateNum = getDateFromFormat(newValue, g_user_date_format);  


                 


      if (startDateNum <= currentDateNum) {  


      g_form.showFieldMsg('Please ensure that the Expiry date is in the future!', 'error');


  return false;


  }


}  


View solution in original post

21 REPLIES 21

dougconnell
Kilo Guru

I don't think using Ajax to validate Client Dates on the Server side could possibly be considered best practice.  

Below is a sample UI Client Script which runs entirely on the client and validates a Variable of type Date in a Catalog Item.

This script checks to see if the 'date_required' (i.e. NewValue) is >= 2 days in the future and not on a weekend.

 

function onChange(control, oldValue, newValue, isLoading, isTemplate) {
 
    if (isLoading || newValue === '') {
        return;
    }
     
    //get the new and current date/time as an object
    var dateObjectNow = new Date();
    var dateObjectNew = new Date(newValue);
    //get the dates in days - also use floor to convert valeus to integers
    var dateNow = Math.floor(dateObjectNow.valueOf()/(1000*60*60*24));
    var dateNew = Math.floor(dateObjectNew.valueOf()/(1000*60*60*24));
    // Get day of week (Sunday = 0)
    var dayOfWeek = dateObjectNew.getDay();
 
    // Check Date if date is 2 or more days in the future and not on the weekend.
    // dateNow is the Date/Time now, whereas dateNew is the date at midnight
    // so dateNew currently equals dateNow -1.  So use 2 in the check below (not 2).
    var msg;
    if (dateNew >= (dateNow + 2) && dayOfWeek > 0 && dayOfWeek < 6) {
        msg = 'Date is OK';
        g_form.hideFieldMsg('date_required',true);
        g_form.showFieldMsg('date_required',msg,'info',false);
    }
    else {
        msg = 'ERROR: Date must be 2 or more days in the future and not on the weekend.';
        g_form.hideFieldMsg('date_required',true);
        g_form.showFieldMsg('date_required',msg,'error',false);
    }
}

tillu
Giga Expert

Validation being at server level or at client? I do not see this as a question of best practice! This depends on the requirement. Personally, if there is a large form to fill in, and a date validation happens at the end of a torture form, I would go through the roof. If it is a small, rapid entry form, it could be done via a business rule. Whichever is your preferred route, one important aspect which is being missed here is that if one goes down the client side script, or a UI policy, the best practice is that you accompany the field validation with an ACL which does not allow list-edit of the same same field from the list. Otherwise, the date would be editable without going into the form and the validation script would not fire. A business rule, on the other hand, will fire both when submitting the form or editing the record from the list.