I want to calculate the age. It should be greater than 18 years.

Tanishka Arora1
Kilo Contributor

I have a variable on catalog item named "date of birth". I want to calculate the age. If the age is less than 18 years then it should alert a message. 

 If I am born on/before 15th Oct 2002, I shouldn’t see this message as today's age is 15th Oct 2020.

5 REPLIES 5

Ankur Bawiskar
Tera Patron
Tera Patron

Hi,

you will have to use onchange client script and GlideAjax for this

1) calculate the difference between today and the date given

2) if the difference is more than 18 years then return the message accordingly

Regards
Ankur

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

Ankur Bawiskar
Tera Patron
Tera Patron

Hi,

sample script below

Script Include: It should be client callable

var calculateUtils = Class.create();
calculateUtils.prototype = Object.extendsObject(AbstractAjaxProcessor, {
    
    getDifference: function(){

        var date = new GlideDateTime(this.getParameter('sysparm_date'));            
        var nowTime = new GlideDateTime();
        
        var diff = gs.dateDiff(date, nowTime, true);
        var years = diff/31556952000; // 1 year is 31556952000 milliseconds
        
        if(parseInt(years) > 18){
        return true;
        }
        else{
        return false;
        }
    },
    
    type: 'calculateUtils'
});

Client Script:

function onChange(control, oldValue, newValue, isLoading) {
    if (isLoading || newValue == '') {
        return;
    }
	
	g_form.hideFieldMsg('date_of_birth'); // give here proper variable name

    var ga = new GlideAjax('calculateUtils');
    ga.addParam('sysparm_name', "getDifference");
    ga.addParam('sysparm_date', g_form.getValue('date_of_birth')); // give here proper variable name
    ga.getXMLAnswer(function(answer){
        if(answer.toString() == 'true'){
            var message = 'You are not allowed to select this date of birth as it is more than 18 years';
            g_form.clearValue('date_of_birth'); // give here proper variable name
			g_form.showFieldMsg('date_of_birth', message, 'error', true);
        }
    });
    //Type appropriate comment here, and begin script below

}

Regards
Ankur

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

if i select 16th oct 2002 then it should give me an error

Hi,

if the validation fails then it would clear the variable and show field message besides that variable

Regards
Ankur

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader