Question

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?

Was it helpful?

Solution 2

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.

OTHER TIPS

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}

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.

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