locked
Help with code to calculate age RRS feed

  • Question

  • Hi there,

    I wan to validate the Birthdate Field and when validated then set the value to new filed Age 

    and if less the 18 the display message .

    I am getting Error Unable to get property getFullYear.

    How can I do this 

    function CalculateAge(birthdate, ondate) 
    {
     // if ondate is not specified consider today's date
        if (ondate == null) { ondate = new Date(); }
        // if the supplied date is before the birthday returns 0 
        if (ondate < birthdate) { return 0; }
        var age = ondate.getFullYear()-birthdate.getFullYear();
        if (birthdate.getMonth() > ondate.getMonth() || (birthdate.getMonth() == ondate.getMonth() && birthdate.getDate() > ondate.getDate()))
      { age--; } 
           Xrm.Page.getAttribute("new_age").setValue(age);
        if (age > 18) {

            alert('msg');

        }
    }


    • Edited by Crm_2013 Saturday, September 21, 2013 4:01 PM
    Saturday, September 21, 2013 3:54 PM

All replies

  • Hi,
    you need to pass to the function a javascript date object as argument, for example:

    // new_birthday is a crm date field that contains the birth date.
    var birthday = Xrm.Page.getAttribute("new_birthday").getValue(); CalculateAge(birthday);

    // or
    var birthdate = new Date(1970, 0, 1); // 1 January 1970
    CalculateAge(birthdate);


    My blog: www.crmanswers.net

    Saturday, September 21, 2013 8:59 PM
  • Hi

    function CalcAge()
    {
        var now = new Date(); //Todays Date   
        var birthday = Xrm.Page.getAttribute("fieldname").getValue(); //Get the Date of Birth value  
         
        var diff = now.getMonth() - birthday.getMonth();  //Check to see if Birthday has already passed
    if (diff > -1) //If Birthday has already occurred   
        {
            var bd1 = now.getFullYear() - birthday.getFullYear();
            //set the age attribute 
            Xrm.Page.getAttribute("setfieldname").setValue(bd1.toString());  
        }
        else //If Birthday has not already occurred  
        {
            var bd2 = now.getFullYear() - birthday.getFullYear() - 1;
            Xrm.Page.getAttribute("setfieldname").setValue(bd2.toString()); 
        }
    }

    Monday, September 23, 2013 7:12 AM