Posted in Code Snippets, CRM, JavaScripts

Calculate Age Based on Birthday Date

Calculate Age Based on Birthday Date :-

Calculating the age from a date of birth field in ms crm form. If Date of Birth field changes, then automatically age can be populated on the Age field. and Date of Birth Cannot be the Future date, once If he selects the future date then It will show the notification as ” Enter the correct Date “.

Date of Birth field Name – “qbb_dateofbirth” datetype is Date.

Age Field schema name is – “qbb_age” datatype is WholeNumber. Make Field Readonly.

Javascript code as follows :

Trigger the following code on field change of date of Birth

function birthdateOnChange(){
 debugger;
 var birthday = Xrm.Page.getAttribute("qbb_dateofbirth").getValue();
 var Todaydate = new Date(); 
 if (birthday != null) {
 if(Todaydate > birthday){
 var age = CalculateAge(birthday,Todaydate);
 Xrm.Page.getAttribute("qbb_age").setValue(age);
 Xrm.Page.getControl("qbb_dateofbirth").clearNotification();
 }
 else{
 var birthday = Xrm.Page.getAttribute("qbb_dateofbirth").setValue(null);
 var birthday = Xrm.Page.getAttribute("qbb_age").setValue(null);
 Xrm.Page.getControl("qbb_dateofbirth").setNotification("Enter valid Date of Birth");
 }
 }
}

function CalculateAge(birthday,Todaydate) {
 debugger; 
 if (Todaydate < birthday) {return 0;}
 var age = Todaydate.getFullYear() - birthday.getFullYear();
 if (birthday.getMonth() > Todaydate.getMonth() || (birthday.getMonth() == Todaydate.getMonth() && birthday.getDate() > Todaydate.getDate()))
 age--;
 return age;
}

5.JPG

Enjoy 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s