Validate text entry based on minimum number of words (not characters) | XM Community
Solved

Validate text entry based on minimum number of words (not characters)

  • 8 July 2019
  • 3 replies
  • 514 views

Userlevel 1
Badge +2
I have a text entry field where respondents must enter a minimum of 100 words (not characters). I'm using the following JavaScript (in add.OnReady) to count and display the number of words entered in the text box. I want to set up a validation that checks to see if the the user has written at least 100 words, effectively preventing them from moving to the next block until they meet the minimum.

var display = $('ACT1_wordCountDisplay');
var questionID = this.questionId;
var textbox =$('QR~' + questionID);
var that = this;
function countWords(s){
s = s.replace(/\\n/g,' '); // newlines to space
s = s.replace(/(^\\s*)|(\\s*$)/gi,''); // remove spaces from start + end
s = s.replace(/[ ]{2,}/gi,' '); // 2 or more spaces to 1
if(s == ''){
return 0;
}else{
return s.split(' ').length;
}
}

textbox.onkeyup = function(e){
display.update(countWords(textbox.value));
console.log(textbox.value);
}
icon

Best answer by fleb 9 July 2019, 10:16

View original

3 replies

Userlevel 5
Badge +6
Hi @ambrubaker,
I think it would be easier to use "Custom validation" with the "Matches Regex" option.
Your expression would be following: `/^\\W*(\\w+\\b\\W*){100,}$/` (taken from here)
Userlevel 1
Badge +2
Hi @fleb,

This appears to work perfectly. Thank you for the assist.
Badge +1
Hi @ambrubaker,

Is there a way to modify your JavaScript to count the words in a text entry field and simply store the information in an embedded data variable ? I do not wish to display the info, simply count the words and store the info for subsequent analysis.

Thanks for your help !

Leave a Reply