Date validation in custom field

rah dev
Tera Contributor

Hi Community,

there are two date fields

rahdev_0-1715346963649.png

there should not be gap between them greater than two years, if it is, then alert message should pop up in the record.

Thanks

1 ACCEPTED SOLUTION

IbrarA
Giga Guru

Hi @rah dev, you can try following client script:

function onChange(control, oldValue, newValue, isLoading) {
    if (isLoading || newValue == '') {
        return;
    }
    var date1 = g_form.getValue('u_date1');
    var date2 = g_form.getValue('u_date2');
    var diff = (new Date(date2) - new Date(date1)) / (1000 * 60 * 60 * 24 * 365);
    if (diff > 2) {
        alert("The difference between Start date and End Date is greater than 2 years.");
    }
}
IbrarA_0-1715347382739.png

 

ibrar

View solution in original post

2 REPLIES 2

IbrarA
Giga Guru

Hi @rah dev, you can try following client script:

function onChange(control, oldValue, newValue, isLoading) {
    if (isLoading || newValue == '') {
        return;
    }
    var date1 = g_form.getValue('u_date1');
    var date2 = g_form.getValue('u_date2');
    var diff = (new Date(date2) - new Date(date1)) / (1000 * 60 * 60 * 24 * 365);
    if (diff > 2) {
        alert("The difference between Start date and End Date is greater than 2 years.");
    }
}
IbrarA_0-1715347382739.png

 

ibrar

johnfeist
Mega Sage
Mega Sage

Hi Rah,

 

You will need a client script and a script include to do what you need.  The client script will be either just that or a catalog client script, depending on the context.  The script include must be client callable.  Your client script will issue an AJAX call to the script include, passing the two date values as strings.  The script include will instantiate two GlideDateTime variables from the passed parameters.  From there you have any of several ways to do the comparison, perhaps something like this:

 

var theStart = new GlideDateTime(sysparm_start);
var theEnd = new GLideDateTime(sysparm__end);
theStart.addYears(2);
var theDif = theStart.compareTo(theEnd);
if (theDif >= 0) {
   return true;
}
return false;

 

Hope that helps.

:{)

Helpful and Correct tags are appreciated and help others to find information faster