Javascript to calculate user's age, based on DOB, check age eligibility, & provide validation alert

nkumich
nkumich Ann Arbor, MI Qubie ✭

A major goal of our recruitment survey is to identify users who are between the ages of 14-24 (target population) and those who are not (not eligible for our study). Currently we ask users for their date of birth (MM/DD/YYYY) and would like to use JS to:

  1. Calculate age, based on the current date
  2. Determine if the age is within our target range (14-24)
  3. Provide a validation alert to the users AND/OR categorize users using embedded data in the categories of eligible/ineligible based on age

Please take a look at the code I have now for the DOB question:

Qualtrics.SurveyEngine.addOnReady(function()
{
var dob_entry = getTextValue();
var split_dob = dob_entry.split("/");
var month = split_dob[0];
var day = split_dob[1];
var year = split_dob[2];
var dob_asdate = new Date(year, month, day);
var today = new Date();
var mili_dif = Math.abs(today.getTime() - dob_asdate.getTime());
var age = (mili_dif / (1000 * 3600 * 24 * 365.25));
within_age_range=(14<age & age<24);

alert(age);
});
Tagged:

Best Answer

  • MohammedAli_Rajapkar
    MohammedAli_Rajapkar Mumbai - India Wizard ✭✭✭✭✭
    Accepted Answer

    The below code is to calculate the age based on the birth year:

    Add an embedded data "UserAge" and the below code will assign the age of the user in it. Then in Survey flow, you can add branch logic to categorize user as eligible or ineligible.

«1

Answers

  • srane
    srane Chicago Qubie ✭

    To calculate age based on current DOB you can use the following code:

    var dob_entry = getTextValue();
    var split_dob = dob_entry.split("/");
    var month = split_dob[0];
    var day = split_dob[1];
    var year = split_dob[2];
    var ageValue = 0;
    var condition1 = parseInt(month+day);

    var today_date = new Date();
    var today_year = (today_date.getFullYear()).toString();
    var today_day = (today_date.getDate()).toString();
    var today_month= (today_date.getMonth()+1).toString();
    var condition2 = parseInt(today_month+today_day);

    if(condition2>=condition1)
    {
    ageValue = parseInt(today_year-parseInt(year));
    }
    else
    {
    ageValue = parseInt(today_year-parseInt(year)-1);
    }

    if(14<=ageValue && ageValue<=24)
    { Qualtrics.SurveyEngine.setEmbeddedData('Validity',1);
    alert('Valid age.');
    }
    else
    { Qualtrics.SurveyEngine.setEmbeddedData('Validity',0);
    alert('Invalid age.');
    }

    You'll need to add an embedded data 'Validity' in your Survey Flow and then use the display logic or survey termination condition on embedded data using the set embedded data.

  • mjs5zx
    mjs5zx Charlottesville, VA Qubie ✭

    Using Mohammedali_Rajapakar_Ugam's method, I can't get the value from the text entry field for QYear to pipe in. I've tried using a form field to ask for the date in YYYY/MM/DD and MM/DD/YYYY formats.

  • TomG
    TomG Raleigh, NC Wizard ✭✭✭✭✭

    I don't remember seeing this question before @mjs5az resurrected it, but the answers given are doing it the hard way and the accepted answer isn't always accurate. You can do everything @nkumich asked for by using moment.js and adding this script to the DOB question:

    Qualtrics.SurveyEngine.addOnPageSubmit(function() {
        var age = moment().diff(moment(jQuery("#"+this.questionId+" .InputText").val()), 'years');
        Qualtrics.SurveyEngine.setEmbeddedData('age', age);
        if(age > 13 && age < 25)  Qualtrics.SurveyEngine.setEmbeddedData('eligible', '1');
    });
    

    Demo survey

  • mjs5zx
    mjs5zx Charlottesville, VA Qubie ✭

    @TomG I'm sorry, I'm not familiar with JS. So, I put this in the question html: but I'm not sure how to edit the JS that you provided. Where do I put the QID? Is there anything else that I need to change? I set an "Age" variable in the survey flow. Thanks so much for your help.

  • mjs5zx
    mjs5zx Charlottesville, VA Qubie ✭

    I got it to work, I didn't need to change anything. My apologies.

  • mjs5zx
    mjs5zx Charlottesville, VA Qubie ✭

    @TomG I want to create a validation message if the age is above > 18. Is there a way to do this without them submitting their response?

  • TomG
    TomG Raleigh, NC Wizard ✭✭✭✭✭
    edited September 2018

    @mjs5zx said:
    @TomG I want to create a validation message if the age is above > 18. Is there a way to do this without them submitting their response?

    @mjs5zx - Yes there is, but your exact requirements aren't clear to me (since the original post wasn't yours). Whatever they are, the solution will be more complicated than what I posted.

  • mjs5zx
    mjs5zx Charlottesville, VA Qubie ✭

    @TomG Basically, I want it to treat it like the baked in content validation and not allow the participant to proceed with the survey if the age is > 18, and to give them an error message. The birthdate is the first question. We've already collected it in a database application (Filemaker) that is passing some information to Qualtrics. It's not in the process currently, but it would probably be a good idea for me to pass the birthdate from Filemaker and create a flag if it doesn't match the birthdate entered into Qualtrics.

  • TomG
    TomG Raleigh, NC Wizard ✭✭✭✭✭

    @mjs5zx - You can do age validation through some JavaScript trickery, but I don't think validation is the best choice. I think best practice is to terminate respondents that don't qualify. Otherwise, you are giving them to opportunity (i.e. encouraging them) to lie in order to move forward.

    For the birthdate you already have, you can assign it to an embedded variable and pipe that embedded variable into your question as the default answer.

  • mjs5zx
    mjs5zx Charlottesville, VA Qubie ✭

    @TomG This works. Thanks so much. Also, I really like how your demo survey automatically adds the '/' to assist with the date format. Would you be willing to help me learn how to do that?

  • TomG
    TomG Raleigh, NC Wizard ✭✭✭✭✭

    @mjs5zx said:
    @TomG This works. Thanks so much. Also, I really like how your demo survey automatically adds the '/' to assist with the date format. Would you be willing to help me learn how to do that?

    @mjs5zx - I'll send you a message.

  • annaj
    annaj Qubie ✭

    @TomG said:

    @mjs5zx said:
    @TomG This works. Thanks so much. Also, I really like how your demo survey automatically adds the '/' to assist with the date format. Would you be willing to help me learn how to do that?

    @mjs5zx - I'll send you a message.

    @TomG Hi! I would be interesting as well in adding the "/" to assist wit the date format. Would it be possible to get your advice on this? Many thanks!

  • annaj
    annaj Qubie ✭

    @TomG In addition, I tried to exclude participants to my survey based on their DOB. I want only people who are between 16 and 99.

    1. I've added in Qualtrics header (in Look & Feel) this piece of code:

    2. I've added this piece of code in the DOB question:
      Qualtrics.SurveyEngine.addOnPageSubmit(function() {
      var age = moment().diff(moment(jQuery("#"+this.questionId+" .InputText").val()), 'years');
      Qualtrics.SurveyEngine.setEmbeddedData('age', age);
      if(age > 15 && age < 100) Qualtrics.SurveyEngine.setEmbeddedData('eligible', '1');
      });

    3. In the Survey Flow, I've added this:
      Branch if eligible is Not Equal to 1 then End of Survey

    Am I missing something?

    Many thanks for your support!
    Best,
    Anais

  • TomG
    TomG Raleigh, NC Wizard ✭✭✭✭✭

    @annaj said:
    Am I missing something?

    You've got all the correct steps. Your code under (1) doesn't display, but if that is correct, it should work.

  • annaj
    annaj Qubie ✭
    edited November 2018

    @TomG Sorry here is the code in (1):

    Is that correct?
    I can't understand why it doesn't work. Do I need to add any embedded data?

  • TomG
    TomG Raleigh, NC Wizard ✭✭✭✭✭

    @annaj said:
    @TomG Hi! I would be interesting as well in adding the "/" to assist wit the date format. Would it be possible to get your advice on this? Many thanks!

    Use cleave.js

  • annaj
    annaj Qubie ✭

    @TomG said:

    @annaj said:
    @TomG Hi! I would be interesting as well in adding the "/" to assist wit the date format. Would it be possible to get your advice on this? Many thanks!

    Use cleave.js

    @TomG Thanks for the hint! Could you please explain me how to use cleave.js? What piece of code should I add in the question?

  • TomG
    TomG Raleigh, NC Wizard ✭✭✭✭✭

    @annaj said:
    @TomG Thanks for the hint! Could you please explain me how to use cleave.js? What piece of code should I add in the question?

    I've answered this before. Try this thread: https://www.qualtrics.com/community/discussion/comment/2682#Comment_2682

  • annaj
    annaj Qubie ✭

    @TomG said:

    @annaj said:
    @TomG Thanks for the hint! Could you please explain me how to use cleave.js? What piece of code should I add in the question?

    I've answered this before. Try this thread: https://www.qualtrics.com/community/discussion/comment/2682#Comment_2682

    @TomG Many thanks! I will check this out!