Age check | XM Community
Skip to main content

Hello,
We want to implement an age check in a survey, where we first ask for the respondents' age in years, then for their date of birth, and if the two are off by more than one year, the survey should end for them. Any ideas how to achieve this? I guess my question is, how do I code to calculate the age from their dob and then store it in embedded data, so I can branch to an end message if the embedded data and the age do not match.
We have set up the age question as a simple text entry, and the dob survey like this:
Qualtrics.SurveyEngine.addOnload(function()
{
  
  //Set years you would like to have available 
  
  var yearFirst = 1958; //Min 1900
  var yearLast = 2004; //Max 2049
  
  
  //This all remains unchanged
  var qid=this.questionId;
  var mo=document.getElementsByName('QR~'+qid+'#1~1')R0];
  var day=document.getElementsByName('QR~'+qid+'#2~1')Q0];
  var yr=document.getElementsByName('QR~'+qid+'#3~1')'0];
    
  var j = yearLast-1898;
  for(i=j;i<151;i++){
    yr.remove(j);
  }
  
  for(i=1;i<=yearFirst-1900;i++){
    yr.remove(1);
  }
  
  function fixer()
  {
    day.options 29].disabled=0;
    day.optionsn30].disabled=0;
    day.optionsi31].disabled=0; 
    if(mo.selectedIndex==2||mo.selectedIndex==4||mo.selectedIndex==6||mo.selectedIndex==9||mo.selectedIndex==11)
    {
      day.optionsc31].disabled=1;
      if(day.selectedIndex==31){day.selectedIndex=30};
      if(mo.selectedIndex==2)
      {
        day.options(30].disabled=1;
        if(day.selectedIndex==30){day.selectedIndex=29};                      
        if(parseInt(yr.optionsIyr.selectedIndex].innerHTML,10)%4!=0)
        {
          day.optionsp29].disabled=1;
          if(day.selectedIndex==29){day.selectedIndex=28}; 
        }
        else
        {
          day.options=29].disabled=0;
        }      
      }
    }
  
  }
                                
  yr.onchange=function(){fixer();};
  mo.onchange=function(){fixer();};


    
});
Screenshot 2022-02-21 at 15.31.42.png
Thanks a lot!!

FloNeb Since you're asking for age in the first question and asking for birthdate in the second question, you can use the below code to calculate the age based on birth date.

var from = "15/09/1994".split("/");
var birthdateTimeStamp = new Date(from[2], from[1] - 1, from[0]);
var cur = new Date();
var diff = cur - birthdateTimeStamp;
// This is the difference in milliseconds
var currentAge = Math.floor(diff/31557600000);
// Divide by 1000*60*60*24*365.25

console.log(currentAge);

Then subtract currentAge and Age value from the question. Based on which you can store True or False in an embedded value.
Now use a text/ graphic type question[In another block let's call this block 2] just to display a quick message saying age did not match which is where you will be placing this script and add a timer question after and end the survey using branch if logic saying if Embedded value: Diff = False, End of Survey.


Thank you, Aanurag_QC .
Sorry about asking again, but do I include the code you sent in the java script of the date of birth question that I sent you? And then where should I subtract the currentAge and Age value?


FloNeb If your JS does work as expected and provides you the age of a person, then you can use that JS in the next question as suggested earlier, store the birth age in a variable and subtract the ages and use the if-else condition within that JS itself.


Aanurag_QC I added the code you suggested and the if else condition to the onload function of the additional block with the fail message:
Qualtrics.SurveyEngine.addOnload(function()
{
/*Place your JavaScript here to run when the page loads*/
var from = "15/09/1994".split("/");
var birthdateTimeStamp = new Date(from[2], from[1] - 1, from[0]);
var cur = new Date();
var diff = cur - birthdateTimeStamp;
// This is the difference in milliseconds
var currentAge = Math.floor(diff/31557600000);
// Divide by 1000*60*60*24*365.25


console.log(currentAge);

var age = ?????
var agecheck = currentAge - age
if(agecheck >"1"){
Qualtrics.SurveyEngine.setEmbeddedData('age_check',  "FALSE");
}
if(agecheck <"-1"){
Qualtrics.SurveyEngine.setEmbeddedData('age_check',  "FALSE");
}
else{
Qualtrics.SurveyEngine.setEmbeddedData('age_check',  "TRUE");
}

});


A few questions:

  1. The var "from" contains a specific date ("15/09/1994") but it should pull the date that was entered by the respondent in the date of birth question, no? How do I do that?

  2. I calculate the var "agecheck" to get the difference from the age they entered ("age") and the calculated age from their date of birth. How do I make sure that "age" is the age that gets pulled from the first question where we ask about their age? I tried to find it but could not.

  3. I understand you suggested to add a different block that shows a message when the age does not check. I only want that message to be shown to those where the age differs. Those respondents for which the age and date of birth match, should not get this message. Shouldn't I put the code above to the Unload function of the date of birth question, and then the next block with the fail message is only shown if the embedded data shows "FAIL"?


Hello FloNeb ,
1) Yes you're correct. Instead of the static value, it should be the value from the question itself. You can store the details either in embedded data, string them along in this format (DD/MM/YYYY) and parse the embedded value in JS instead of the 15/09/1994 or you can combine the values in JS as well.
2) You need to parse the stored value from the question into the JS you can go with something like var a= ${q://QID5/ChoiceTextEntryValue}. This will store your value from the question and subtract it accordingly.
3) The reason why I asked you to use a separate block is that you can use branch if conditions in the survey flow to view that particular block only if embedded value age check = false meaning that the age difference is greater than a year and add end of survey after the block such that the survey ends for these users. if the age check =true it will continue with the rest of the survey.


Thanks again, Aanurag_QC .
RE: 1) I set an embedded data in the survey flow and then in the Unload function of the birthdate question like this:
Qualtrics.SurveyEngine.setEmbeddedData("dob", mo/day/yr);
and then updated the code you had sent to:
var from = "dob".split("/");
var birthdateTimeStamp = new Date(from[2], from[1] - 1, from[0]);
var cur = new Date();
var diff = cur - birthdateTimeStamp;
// This is the difference in milliseconds
var currentAge = Math.floor(diff/31557600000);
// Divide by 1000*60*60*24*365.25
I assume I will have to change the code in birthdateTimeStamp as well since I want it in the MM/DD/YYYY format. I cannot follow your code. Could you advise how I have to change it?

RE: 3) That makes sense. But don't I have to include the code in the unload function of the birthdate question, then? If I include it in the second block, it won't be able to branch anymore, will it?


Hello FloNeb

-- Use the below JS to use a date picker rather than using a matrix table use a date picker in a text --entry question:
Qualtrics.SurveyEngine.addOnload(function()
{
//jQuery("#"+this.questionId+" .InputText").flatpickr({enableTime: true, altInput: true, altFormat: "Y-m-d h:i K", dateFormat: "Y-m-d h:i K", minDate:"today", maxDate: new Date().fp_incr(365)});
jQuery("#"+this.questionId+" .InputText").flatpickr({enableTime: false, altInput: true, altFormat: "d/m/Y ", dateFormat: "d/m/Y ", time_24hr: false});
});

Qualtrics.SurveyEngine.addOnReady(function()
{
  /*Place your JavaScript here to run when the page is fully displayed*/

});

Qualtrics.SurveyEngine.addOnUnload(function()
{
  /*Place your JavaScript here to run when the page is unloaded*/

});

-- Add these links under source code in --> look and feel --> General --> Header--
">https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.21.0/moment.min.js">
https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css" rel="stylesheet" />">https://cdn.jsdelivr.net/npm/flatpickr">

-- Create another text/graphic question that should be placed in a new block --

Qualtrics.SurveyEngine.addOnReady(function()
{

var age_years = moment().diff("${q://QID187/ChoiceTextEntryValue}", 'years');

var now = moment();
var before = moment("${q://QID187/ChoiceTextEntryValue}", }"MM-DD-YYYY", "DD-MM-YYYY, moment.ISO_8601"] );


var diffDuration = moment.duration(now.diff(before));
var years= diffDuration.years(); // 8 years
var months = diffDuration.months(); // 5 months
var days = diffDuration.days(); 


var final = years+" years "+months+" months and "+days+"days";
var age_final = age_years;



});

age_final is what will calculate the age based on DOB

You can later use if and else statement within the same JS to check and compare the age provided subtracting it from the age_final value.



Aanurag_QC, Sorry, but in the last part of the code that you sent, the "var age_final = age_years;" just takes the value from age_years, so I am confused why you do all the steps in between if age_final ignores them.
Also, let me reiterate my previous concern. If the difference between the two variables is only calculated in the new block, I cannot branch this new block based on the difference of the age, can I? Shouldn't I calculate the difference when the participants enter the date of birth?
I tried to make it work but failed with this code including the if else statement. Could you take a look please?
var age_years = moment().diff("${q://QID81/ChoiceTextEntryValue}", 'years');


var now = moment();


var before = moment("${q://QID81/ChoiceTextEntryValue}", "MM-DD-YYYY", "DD-MM-YYYY, moment.ISO_8601"] );






var diffDuration = moment.duration(now.diff(before));


var years= diffDuration.years(); // 8 years


var months = diffDuration.months(); // 5 months


var days = diffDuration.days(); 


var final = years+" years "+months+" months and "+days+"days";


var age_final = age_years;

var age = "${q://QID74/ChoiceTextEntryValue}"; 

var agecheck = age_final - age;

if(agecheck >"1"){
Qualtrics.SurveyEngine.setEmbeddedData('age_check',  "FALSE");
}
else if(agecheck <"-1"){
Qualtrics.SurveyEngine.setEmbeddedData('age_check',  "FALSE");
}
else{
Qualtrics.SurveyEngine.setEmbeddedData('age_check',  "TRUE");
}


https://community.qualtrics.com/XMcommunity/discussion/comment/43971#Comment_43971Hello FloNeb Please refer to the updated code which I have tweaked per your requirement

Qualtrics.SurveyEngine.addOnReady(function()
{

var age_years = moment().diff("${q://QID1/ChoiceTextEntryValue}", 'years');

var now = moment();
var before = moment("${q://QID1/ChoiceTextEntryValue}", ["MM-DD-YYYY", "DD-MM-YYYY, moment.ISO_8601"] );


var diffDuration = moment.duration(now.diff(before));
var years= diffDuration.years(); // 8 years
var months = diffDuration.months(); // 5 months
var days = diffDuration.days(); 


//var final = years+" years "+months+" months and "+days+"days";
//var age_final = age_years+" years ";

var age_provided = "${q://QID74/ChoiceTextEntryValue}";

var agecheck = age_provided - years;

if(agecheck >"1"){
Qualtrics.SurveyEngine.setEmbeddedData('agecheck', "FALSE");
}
else if(agecheck <"-1"){
Qualtrics.SurveyEngine.setEmbeddedData('agecheck', "FALSE");
}
else{
Qualtrics.SurveyEngine.setEmbeddedData('agecheck', "TRUE");
}

Qualtrics.SurveyEngine.setEmbeddedData("Age", age_final );
//Qualtrics.SurveyEngine.setEmbeddedData("Date_Provided", agecheck );

});

Please note that the agecheck needs to be saved as embedded data where you're storing the value true or false.

Also, the reason why I asked to use this code in a new block is because the JS needs to fetch values that are stored earlier. Example the date of birth that you selected, gets stored as a value to the question only when you hit the next button since my code is a JS code and not Jquery. If the code does not find the value it will throw NaN as result.


Leave a Reply