<p>A requirement for an ASP.Net 2.0 project I'm working on limits a certain field to a max of 10 words (not characters). I'm currently using a CustomValidator control with the following ServerValidate method:</p>

<pre><code>Protected Sub TenWordsTextBoxValidator_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles TenWordsTextBoxValidator.ServerValidate
    '' 10 words
    args.IsValid = args.Value.Split(" ").Length &lt;= 10
End Sub
</code></pre>

<p>Does anyone have a more thorough/accurate method of getting a word count?</p>

[{'answer_id': 52610, 'author': 'Michael Haren', 'author_id': 29, 'author_profile': 'https://Stackoverflow.com/users/29', 'pm_score': 3, 'selected': False, 'text': "<p>You can use one of the builtin validators with a regex that counts the words.</p>\n\n<p>I'm a little rusty with regex so go easy on me:</p>\n\n<pre><code>(\\b.*\\b){0,10}\n</code></pre>\n"}, {'answer_id': 52625, 'author': 'Joel Coehoorn', 'author_id': 3043, 'author_profile': 'https://Stackoverflow.com/users/3043', 'pm_score': 0, 'selected': False, 'text': "<p>I voted for mharen's answer, and commented on it as well, but since the comments are hidden by default let me explain it again:</p>\n\n<p>The reason you would want to use the regex validator rather than the custom validator is that the regex validator will also automatically validate the regex client-side using javascript, if it's available.  If they pass validation it's no big deal, but every time someone fails the client-side validation you save your server from doing a postback.</p>\n"}, {'answer_id': 52737, 'author': 'travis', 'author_id': 1414, 'author_profile': 'https://Stackoverflow.com/users/1414', 'pm_score': 2, 'selected': True, 'text': '<p>This regex seems to be working great:</p>\n\n<pre><code>"^(\\b\\S+\\b\\s*){0,10}$"\n</code></pre>\n\n<p><strong>Update</strong>: the above had a few flaws so I ended up using this RegEx:</p>\n\n<pre><code>[\\s\\x21-\\x2F\\x3A-\\x40\\x5B-\\x60\\x7B-\\xBF]+\n</code></pre>\n\n<p>I <code>split()</code> the string on that regex and use the <code>length</code> of the resulting array to get the correct word count.</p>\n'}]
['https://Stackoverflow.com/questions/52591', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1414/']