4

I am trying to validate length of a string in a TextBox. Controls on page defined as follows:

<asp:TextBox runat="server" ID="TB" /> <asp:RangeValidator runat="server" ID="RV" MinimumValue="3" MaximumValue="20" ControlToValidate="TB" Type="String" /> 

But when page runs there is run time error occurred

The MaximumValue 20 cannot be less than the MinimumValue 3

1
  • RangeValidator is used to validate a range of numbers, not the range in the length of strings. Commented Jun 21, 2011 at 12:48

4 Answers 4

13

You mention Type incorrect, it should be Type="Integer" instead Type="String"

Sign up to request clarification or add additional context in comments.

3 Comments

Would changing the type to integer, help the user in validating the length of string?
Thanks Muhammad. I have had a similar problem. I have defined rangevalidator for integer values, but I haven't specified Type attribute. I noticed several times that if textbox in gridviewrow had have rangevalidator from 1 to 10, only 1 and 10 values were accepted by validator. I think that validator use string type if it is not specified.
This answer does not match the question. Specifying Type="Integer" will not cause the RangeValidator to validate the length of the Text attribute. It only causes the string to be parsed as an integer.
4

Just use TextBox's MaxLength propery. That is used to Get/Set maximum number of characters allowed in the text box.

For minimum length you'll need to use a CustomValidator. In that call a js function which checks the length of the string.

Try this:

<asp:TextBox runat="server" ID="TB" /> <asp:CustomValidator runat="server" ID="CustomValidator1" ControlToValidate="TB" Text="The text length should be between 3 and 20" ClientValidationFunction="clientValidate" Display="Dynamic"> </asp:CustomValidator> <script type="text/javascript"> function clientValidate(sender, args) { if (args.Value.length < 3 ||args.Value.length > 20) { args.IsValid = false; } } 

Comments

3

You can not validate the length of a TextBox using a RangeValidator !! RangeValidator is used to validate the value of a field, not the length of this value.

To do that you can use other ways as CustomValidator.

Comments

0

The syntax that worked for me correctly

 <asp:RegularExpressionValidator ID="RegularExpressionValidator34" runat="server" ControlToValidate="fname" Display="Dynamic" ErrorMessage="email is required" ForeColor="Red" SetFocusOnError="True" ValidationExpression="(\s|.){5,10}"> Length must between (5-10) characters</asp:RegularExpressionValidator> 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.