使用自定义验证器进行 ASP.Net 字数统计
我正在处理的 ASP.Net 2.0 项目的要求将某个字段限制为最多 10 个单词(不是字符)。 我目前正在使用带有以下 ServerValidate 方法的 CustomValidator 控件:
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
是否有人有更彻底/准确的方法来获取字数统计?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我投票支持 mharen 的答案,并对它发表了评论,但由于默认情况下评论是隐藏的,让我再次解释一下:
您想要使用正则表达式验证器而不是自定义验证器的原因是正则表达式验证器也会自动使用 javascript 验证正则表达式客户端(如果可用)。 如果他们通过了验证,那就没什么大不了的,但是每次有人未通过客户端验证时,您就可以避免服务器进行回发。
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.
这个正则表达式似乎工作得很好:
更新:上面有一些缺陷,所以我最终使用了这个正则表达式:
我
split()
该正则表达式上的字符串并使用结果数组的length
以获得正确的字数。This regex seems to be working great:
Update: the above had a few flaws so I ended up using this RegEx:
I
split()
the string on that regex and use thelength
of the resulting array to get the correct word count.您可以将内置验证器之一与用于计算单词数的正则表达式结合使用。
我对正则表达式有点生疏,所以对我宽容一些:
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: