The CreatorCon Call for Content is officially open! Get started here.

Data field validation in native UI using Client Script

ankitaankit
Tera Contributor

Hello Team,

Please help me with the below requirement which is not working for me in certain cases.

I have Onchange client script written in ServiceNow for the field Date prolongation (Date/Time), which checks if Date prolongation (Date/Time) is smaller than End date (Date) then it's giving an alert and clearing the value, but it's not working if user is selecting date a per below format,

Start date: 18.12.2024
End date: 31.12.2024
Date prolongation: 30.12.2024 11:47:22 ---> Not working If user have this Date format.

Start date: 2024-12-18
End date: 2024-12-31
Date prolongation: 2024-12-30 12:00:41 ---> working for this format and other formats like
MM-dd-yyyy
dd/mm/yyyy
dd-MM-yyyy
yyyy-MM-dd

 

This is my code

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

var selectedEndDate = g_form.getValue('u_end_date');
var selectedProlongationDate = new Date(getDateFromFormat(newValue, g_user_date_time_format));

selectedProlongationDate.setUTCHours(0, 0, 0, 0);

if (new Date(selectedEndDate).getTime() > selectedProlongationDate.getTime()) {
g_form.clearValue('u_date_prolongation');
alert("Lease Date Prolongation must be greater than End Lease Date.");
return false;
}
}

 

Regards!!

Ankita

1 REPLY 1

Ashish Parab
Mega Sage
Mega Sage

Hello @ankitaankit ,

 

Please try the below script:

 

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

    // Get the values of End Date and Date Prolongation
    var selectedEndDate = g_form.getValue('u_end_date');
    var prolongationDateTime = new Date(newValue);

    // Extract the date part from the Date Prolongation
    var prolongationDate = new Date(prolongationDateTime.getFullYear(), prolongationDateTime.getMonth(), prolongationDateTime.getDate());

    // Convert End Date to a comparable date object
    var endDate = new Date(selectedEndDate);
	
    if (prolongationDate < endDate) {
        g_form.clearValue('date_prolongation');
        alert("Lease Date Prolongation must be greater than End Lease Date.");
        return false;
    }
}

 

 

Please mark this as "correct" and "helpful" if you feel this answer helped you in anyway.

 

Thanks and Regards,

Ashish