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

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

  • July 8, 2019
  • 3 replies
  • 1382 views

ambrubaker
Level 1 ●
Forum|alt.badge.img+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); }

Best answer by fleb

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)

3 replies

fleb
Level 3 ●●●
Forum|alt.badge.img+6
  • Level 3 ●●●
  • Answer
  • July 9, 2019
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)

ambrubaker
Level 1 ●
Forum|alt.badge.img+2
  • Author
  • Level 1 ●
  • July 9, 2019
Hi @fleb, This appears to work perfectly. Thank you for the assist.

Forum|alt.badge.img+1
  • August 27, 2019
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 !