Question

I want to use an ASP.NET RegularExpressionValidator to limit the number of words in a text box. (The RegularExpressionValidator is my favoured solution because it will do both client and server side checks).

So what would be the correct Regex to put in the RegularExpressionValidator that will count the words and enforce a word-limit? For, lets say, 150 words.

(NB: I see that this question is similar, but the answers given seem to also rely on code such as Split() so I don't think any of them could plug into a RegularExpressionValidator which is why I'm asking again)

Was it helpful?

Solution

Since ^ and $ is implicitly set with RegularExpressionValidators, use the following:

(\S*\s*){0,10}

The 0 here allows empty strings (more specifically 0 words) and 150 is the max number of words to accept. Adjust these as necessary to increase/decrease the number of words accepted.

The above regex is non-greedy, so you'll get a quicker match verses the one given in the question you reference. (\b.*\b){0,10} is greedy, so as you increased the number of words you'll see a decrease in performance.

OTHER TIPS

Here is a quick reference for regular expressions: http://msdn.microsoft.com/en-us/library/az24scfc.aspx

You can use this site to test the expressions: http://regexpal.com/

Here is my regex example that works with both minimum and maximum word count (and fixes bug with leading spacing):

^\s*(\S+\s+|\S+$){10,150}$

Check this site:

http://lawrence.ecorp.net/inet/samples/regexp-validate.php#count

its javascript regex, but is very similar to asp.net

its something like this:

(\b[a-z0-9]+\b.*){4,}

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top