Date/Time field values is switching back and forth on form

TerryC03
Tera Guru

Hello,

 

I have a catalog client script that is using a script include to check for weekends and holidays between the hours of 8 - 5 (8-5 weekdays excluding holidays calendar). If the client script receives an answer of true from the glideAjax, it has detected a weekend or holiday, and moves the date by one until the glideAjax returns false. However, if I wanted to then select manually another weekday, the value in the fields constantly switches between the old value and the newly selected value. If I select another value while this is happening it switches through those values as well. How may I prevent this.

 

Client script:

function onChange(control, oldValue, newValue, isLoading) {
    // Check if the form is loading or the newValue is empty, then exit
    if (isLoading || newValue === '') {
        return;
    }

    // Get the selected date from the 'access_start_date' field
    var selectedDateTime = g_form.getValue('access_start_date');
    
    // Convert the selected date into a JavaScript Date object
    var currentDate = new Date(selectedDateTime);

    // Function to format date to 'yyyy-MM-dd HH:mm:ss'
    function formatDate(date) {
        return date.getFullYear() + '-' +
            ('0' + (date.getMonth() + 1)).slice(-2) + '-' +
            ('0' + date.getDate()).slice(-2) + ' ' +
            ('0' + date.getHours()).slice(-2) + ':' +
            ('0' + date.getMinutes()).slice(-2) + ':' +
            ('0' + date.getSeconds()).slice(-2);
    }

    // Function to call GlideAjax and validate the date
    function validateAndAdjustDate(date) {
        var ga = new GlideAjax('DateValidator');
        ga.addParam('sysparm_name', 'validateDate');
        ga.addParam('selectedDate', formatDate(date));

        ga.getXMLAnswer(function(response) {
            var answer = response;

            if (answer === "true") { // If the date is a holiday or weekend
                g_form.addErrorMessage('The selected date falls on a non-working day (weekend or holiday). Adding one day.');

                // Add one day to the date
                date.setDate(date.getDate() + 1);

                // Call the function again with the updated date to validate it
                validateAndAdjustDate(date);
            } else {
                // When Script Include returns false, meaning the date is valid, update the field
				//g_form.clearValue('access_start_date');
               g_form.setValue('access_start_date', formatDate(date));
            }
        });
    }
    // Start the validation process by checking the selected date
    validateAndAdjustDate(currentDate);
}