views:

1231

answers:

3

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:

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 method of getting a word count?

+3  A: 

You can use one of the builtin validators with a regex that counts the words.

I'm a little rusty with regex so go easy on me:

(\b.*\b){0,10}
Michael Haren
The reason you would want to do this is that the built-in regex validator will also automatically validate client-side with javascript for you. So if they fail validation, you save a postback.
Joel Coehoorn
Unfortunately this regex isn't matching correctly, I'll play with it to see if I can get it to work though. Thanks!
travis
A: 

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:

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.

Joel Coehoorn
Joel, thanks for clarifying my choice!Regarding comments: yes, I think it'd be nice if the first few on each answer were expanded by default. Or at least highlighted a little more.
Michael Haren
The extra postback is irrelevant in this case but I think I'll see if I can get the regex working anyways. Thanks!
travis
+1  A: 

This regex seems to be working great:

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

Update: the above had a few flaws so I ended up using this RegEx:

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

I split() the string on that regex and use the length of the resulting array to get the correct word count.

travis