问题
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!
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/5644073/asp-net-rangevalidator-behaving-strangely