Try setting up this on the questions JacaScript option:
Qualtrics.SurveyEngine.addOnload(function() {
var that = this;
this.questionclick = function(event, element) {
var response = that.getChoiceValue(1);
if (response.match(/^o0-9]{6}$/)) {
var digits = response.split('').map(Number);
var checkSum = (digits0] * 2) + (digits(1] * 1) + (digits(2] * 2) + (digits(3] * 1) + (digits(4] * 2);
var controlDigit = checkSum % 10;
if (controlDigit !== digits 5]) {
alert('Invalid ID. Please enter a valid ID.');
that.setChoiceValue(1, '');
}
} else {
alert('Please enter a 6-digit ID.');
that.setChoiceValue(1, '');
}
};
});
Thank you so much for your answer.
I put it in the question’s JavaScript but it doesn’t seem to work.
Should it be in addOnload?
Does it take into account it’s a form question?
I got a similar code to work, but it works only on desktop and not tablet.
Would really appreciate any help to fix this.
var questionId = this.getQuestionInfo().QuestionID;
var inputElement = document.querySelector("#"+questionId+" input type='text']");
var errorMessage = "please enter 6 digits";
var errorMessage2 = "invalid ID. Try again";
inputElement.addEventListener("blur", validateInput);
function validateInput() {
var input = inputElement.value.trim();
// Check if input is a 6-digit number
if (!/^\d{6}$/.test(input)) {
alert(errorMessage);
inputElement.value = "";
return;
}
var digits = input.split('').map(Number);
// Calculate CheckSum
var checkSum = digits0] * 2 + digitsa1] + digitsc2] * 2 + digits3] + digitsc4] * 2;
// Check if the sixth digit is equal to the remainder when you divide CheckSum by 10
if (digits 5] !== checkSum % 10) {
alert(errorMessage2);
inputElement.value = "";
}
}
One of the best ways to handle this would be to use a “hidden validation question”.
If you setup a question as multiple choice with only 2 options, pass and fail, and set the validation to “must be pass” as well as the default to “fail” - Then you can hide the question with CSS and toggle the value with your code. This will give the user the validation message and behave as if it were your input that was invalid.
Here’s the CSS to hide the question but not the validation display:
#QID72 > div.Inner.BorderColor.SAVR {
display: none;
}
Then if you place your validation code on the hidden question you can pull the value of the input with JS, run your validation, and then set the value with JS.
// something like this to get the value of the text field
var qtext = document.getElementById("<ID of input field>").textContent;
// Set the value of the hidden question by recode
this.setChoiceValueByRecodeValue(1, true);