Javascript – Birthday

This is hopefully a useful javascript snippet.

Sometimes capturing a contacts date of birth is important often this is because certain products are age specific. For example you might not be able to take a life insurance product above a certain age or some products might mean you need to be 18+ to purchase. In these circumstances the operator actually needs to see the persons age.

Several times I have used a quick change to alter the caption of the date of birth field to include age. I also added a simple change to let the operator know its someone’s birthday as it might be nice to recognise this whilst speaking to the customer.

My contact form looks like this ….


I’ve based my code on the contact entity and date of birth field. But you could easily adapt to work with other entities and attributes. Like anniversary on contact or maybe you’d like to know how long an account has been with your organisation etc.

To achieve this you can use the following javascript ….

function BirthDateFunction() {
  var birthDate = Xrm.Page.getAttribute("birthdate").getValue();
  var birthDateControl = Xrm.Page.ui.controls.get("birthdate");
  if(birthDate != "" && birthDate != null) {
    var age = CalculateAge(birthDate);
    var newLabel = "Date Of Birth (" + age + ")";
  } else {
    var newLabel = "Date Of Birth";

function CalculateAge(birthDate) {
    birthDate = new Date(birthDate);
    var todayDate = new Date();

    var years = (todayDate.getFullYear() - birthDate.getFullYear());

    if (todayDate.getMonth() < birthDate.getMonth() || 
        todayDate.getMonth() == birthDate.getMonth() && todayDate.getDate() < birthDate.getDate()) {

 if(todayDate.getMonth() == birthDate.getMonth() && todayDate.getDate() == birthDate.getDate()) {
//    alert("Say happy birthday!");
       Xrm.Page.ui.setFormNotification("Say Happy Birthday!!!", "INFO", "1"); 

    return years;

Then from the onchange event of the contacts date of birth and in the onload event of the contact form simply add one line of code.


NOTE: I have recently updated this code to display a notification on someone’s birthday instead of an alert. This is because the new turbo forms process JavaScript differently! The alert was displaying before the form had rendered but the notification displays correctly.

Leave a Reply

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

You are commenting using your 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