ASP.Net word count with a custom validator

巧了我就是萌 提交于 2019-12-05 20:48:05

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}

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.

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.

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