ASP.Net word count with custom validator

Requirement for an ASP.Net 2.0 project I am working on limiting a specific field to a maximum of 10 words (not characters). I am currently using a CustomValidator control with the following ServerValidate method:

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 <= 10 End Sub 

Does anyone have a more thorough / accurate word count method?

+3
source share
3 answers

This regex seems to work fine:

 "^(\b\S+\b\s*){0,10}$" 

Update : The above had several flaws, so I ended up using this RegEx:

 [\s\x21-\x2F\x3A-\x40\x5B-\x60\x7B-\xBF]+ 

I split() string in this regex and use the length resulting array to get the correct number of words.

+1
source

You can use one of the built-in validators with a regular expression that counts words.

I'm a little rusty with regex, so itโ€™s easy on me:

 (\b.*\b){0,10} 
+4
source

I voted for mharen's answer and commented on this as well, but since the comments are hidden by default, let me explain this again:

The reason you want to use the regex validator rather than the custom validator is because the regex checker also automatically validates the regex client side using javascript if available. If they pass the test, it does not matter much, but every time someone fails when checking on the client side, you save your server from postback.

0
source

All Articles