Servicenow

HARSHA GOWDA R
Tera Contributor
function onSubmit() {

    var terminationDate = g_form.getValue('actual_end_date');
    var extensionDate = g_form.getValue('contractor_extension_date');


    // Check if Extension date is before Termination date
    if (extensionDate <= terminationDate) {

        // Prevent the form from being submitted
        alert('Extension date cannot be before or on the Termination date.');
        return false; // This prevents the form from being submitted
    }


    // If validation passes, allow the form to be submitted
    return true;
}
This code is not working for read only field.
Case: On portal the termination date is read only and the date is populating based on user we select,if i select past date the form is getting submitted.It should save only when the extended date is selected as future
HARSHAGOWDAR_0-1718864932575.png

 

3 REPLIES 3

Community Alums
Not applicable

Hi @HARSHA GOWDA R ,

I checked your problem in my PDi anit works for me there is no issue with code may be you can change the UI Type to ALL

SarthakKashyap_0-1718867002928.png

Please mark my answer correct and helpful if this works for you

Thanks and Regards 

Sarthak

PankajP
Tera Contributor

Hi @HARSHA GOWDA R 

I have made some changes in your code and its working.....

Try this code

 

function onSubmit() {
   //Type appropriate comment here, and begin script below
   var terminationDate = g_form.getValue('actual_end_date');
    var extensionDate = g_form.getValue('contractor_extension_date');

    // Check if both dates are not empty
    if (terminationDate && extensionDate) {
        // Convert the dates to JavaScript Date objects
        var terminationDateObj = new Date(terminationDate);
        var extensionDateObj = new Date(extensionDate);

        // Check if the extension date is before or on the termination date
        if (extensionDateObj <= terminationDateObj) {
            // Prevent the form from being submitted
            alert('Extension date cannot be before or on the Termination date.');
            return false; // This prevents the form from being submitted
        }
    }
    // If validation passes, allow the form to be submitted
    return true;
}
 
Mark Correct or Helpful if it helps.

Slava Savitsky
Giga Sage

g_form.getValue() method returns the field value as a string. Comparing strings is not the same as comparing dates and can lead to unexpected results. You need to convert the strings to dates while taking care about the date format. Only then you can compare the values correctly.