Restrict date selection on date picker

reza1921
Tera Contributor

Hi all,

 

I have a catalog item that has a field where the user can select a collection date for their requested item. 

 

I want the default date to be 7 days from the time it was logged and don't want the users to be able to select a date less than 7 days i.e. if the request is being logged on the 1st of June, the date picker should default to 7 days which is 8th June and not be able to select any date between today and the 8th. However, they can choose a date after the 8th. 

 

I created a client script however it does not restrict the user from selecting a date in the past and a date with less than 7 days.

 

function onLoad() {
var preferredDateField = g_form.getControl('preferred_date_time_for_collection');
var defaultDate = new Date();
defaultDate.setDate(defaultDate.getDate() + 7); // Calculate 7 days from today

// Set minimum date in the date picker
preferredDateField.setAttribute('min', defaultDate.toISOString().split('T')[0]);
}

2 REPLIES 2

Amit Verma
Kilo Patron
Kilo Patron

Hi @reza1921 

 

Please have a look on the below post which could be helpful and an efficient way to handle this :

https://www.servicenow.com/community/developer-articles/no-code-date-validations-through-catalog-ui-...

 

Thanks and Regards

Amit Verma


Please mark this response as correct and helpful if it assisted you with your question.

SidharthReddy
Tera Contributor

@reza1921    

Please use the Below Which may helps you. Change the Field names as per your requirement .

clint script : 

var getDate = g_form.getValue("number");
   
    var gaDate = new GlideAjax("getDateAjax");
    gaDate.addParam("sysparm_name", "getDateIncident");
    gaDate.addParam("sysparm_date", getDate);
    gaDate.getXML(callback);

    function callback(response) {
        var answer = response.responseXML.documentElement.getAttribute("answer");
        g_form.setValue("u_auto_update_date" ,answer);
    }
 
Script Include : 
 
var getDateAjax = Class.create();
getDateAjax.prototype = Object.extendsObject(AbstractAjaxProcessor, {


    getDateIncident: function() {



        var incDate = this.getParameter("sysparm_date");
        var grInc = new GlideRecord("incident");
        grInc.addQuery("number", incDate);
        grInc.query();
        if (grInc.next()) {
            var gdt =  new GlideDateTime(grInc.u_today_date);
            gdt.addDays(1);
            gs.addInfoMessage(gdt.getDate());
            return gdt;





        }




        type: 'getDateAjax'
    }
});
 
SidharthReddy_0-1719378914333.png

 

SidharthReddy_1-1719378947451.png

 

SidharthReddy_2-1719378966559.png

 

SidharthReddy_3-1719378995389.png