ASP.Net word count with a custom validator

扶醉桌前 提交于 2019-12-07 14:26:23

问题


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?


回答1:


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}



回答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.




回答3:


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.



来源:https://stackoverflow.com/questions/52591/asp-net-word-count-with-a-custom-validator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!