How to select only future date in date field using onsubmit client script

sriram7
Tera Contributor

Hi Team,

 

I have date field called return date. In that date field I need to select only present and future dates.

I can achieve this using ui policy, but I want to using client script.

11 REPLIES 11

Hi @sriram7 ,

 

Can you try below code and validate

function onSubmit(){

  var dateVal=new Date(g_form.getValue('return_date'));
 var todayDateNum = new Date();
   if(dateVal < todayDateNum) {
   g_form.addErrorMessage("Selected date cannot be less than today's date");
  return false;
    } 
return true;
}

 

Hi @Manmohan K ,

 

For today's date also it is showing error message. Error message needs to show only for past dates.

Hi @sriram7 , If you want to display the error message when you are clicking on Submit then

- create a hidden field(valid_date) with default value 'Yes'.

- Write an UI Policy to validate the selected date and set the value of hidden field 'valid_date' to yes/now using Run Script option of UI policy.

 

Pravindra1_1-1685344654622.png

 

 

Pravindra1_0-1685344526112.png

 

Then write an On-Submit Client Script as below to check if valid date is selected and display error message:

Pravindra1_2-1685344816483.png

 

 

 

 

 

Devender Kumar
Tera Guru
Tera Guru

Hi @sriram7 

 

Please write the onChange Client Script like this

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

    //Type appropriate comment here, and begin script below
    var d = getDateFromFormat(newValue, g_user_date_format);
    var today = new Date();
    if (d < today) {
        alert('The date value cannot be before the current date and time. Please correct.');
        g_form.clearValue("access_date");
    }
}

 

If my answer resolves your issue then don't forget to mark it as correct and helpful.

Regards

Devender Kumar

SN_Learn
Kilo Patron
Kilo Patron

Hi @sriram7 ,

 

Please try the solution proposed in the thread below:

 

https://www.servicenow.com/community/developer-forum/client-script-compare-a-field-date-with-current...

 

If my answer helped you in any way, please then mark it as helpful or correct.

----------------------------------------------------------------
Mark this as Helpful / Accept the Solution if this helps.