ASP.NET RangeValidator 行为异常
它的类型属性设置为字符串,最小值= 0,最大值= 100。
我想确保输入的数据不会超过数据库中定义的列长度。
现在,当我测试它时,即使我输入一两个字母,它总是显示错误消息!
It's type attribute is set to string and it's min value = 0 and the max value = 100.
I want to insure that the data entered won't exceed the column length defined in the database.
Now when I test it, it always display the error message even if I entered one letter or two!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为此,您应该使用正则表达式验证器。 RangeValidators 不适用于字符串长度。将 ValidationExpression 设置为
.?
之类的内容,或者您可以将其缩小为\S?
或\w?
之类的内容或您想要的内容。另外,如果您使用的文本框不处于多行模式(并且如果最大值是一个字符,则没有理由这样做),您只需在控件上设置
MaxLength="1"
,然后你根本不需要验证器。编辑:如果您确实想在多行 TextBox 上指定大于 1 的最大长度,则可以如上所述使用 RegularExpressionValidator,但设置
ValidationExpression=".{0,100}" 最大长度为 100。 提供了有关正则表达式量词的更多信息在这里。
如果您有一个单行文本框,只需将其 MaxLength 属性设置为所需的最大值,并且它不允许任何长度超过该值;不需要验证器。
如果您想做任何涉及在用户键入时实时检测长度的事情,那就更复杂了,您将需要 JavaScript。您还应该在服务器端验证输入,因为任何关闭 JavaScript 的用户都可以绕过客户端验证。
You should use a RegularExpressionValidator for this. RangeValidators aren't for string lengths. Set the ValidationExpression to something like
.?
, or you can narrow it to something like\S?
or\w?
or something if you want.Also, if you're working with a TextBox that's not in MultiLine mode (and there's no reason it would be if the max is one character) you can just set
MaxLength="1"
on the control and you won't need a validator at all.EDIT: If you do want to specify a max length greater than one on a multiline TextBox, you can use a RegularExpressionValidator as described above, but set
ValidationExpression=".{0,100}"
for a maximum length of 100. More information on regex quantifiers is available here.If you have a single-line TextBox, just set its MaxLength attribute to the desired maximum, and it won't allow anything longer than that; no validator required.
If you want to do anything involving real-time detection of the length as the user types it, that's more complicated and you'll need JavaScript. You should also still validate the input server-side, because any user with JavaScript turned off will be able to bypass client-side validation.
将控件上的“MaxLength”属性设置为 1。此 MSDN 页面 描述了该属性及其用法。
RangeValidator 验证输入的值而不是长度,因此您使用验证器将有效输入限制为 {0, 1}。
Set the "MaxLength" property on the control to 1. This MSDN page describes the property and its usage.
RangeValidator validates the value of the input not the length, therefore you are limiting the valid inputs to {0, 1} with your validator.