Validate text entry based on minimum number of words (not characters) | XM Community
Skip to main content
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);

}
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)
Hi @fleb,



This appears to work perfectly. Thank you for the assist.
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