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

Muhammad Akhtar
  • 51,913
  • 37
  • 138
  • 191
Pankaj Agarwal
  • 11,191
  • 12
  • 43
  • 59
  • `RangeValidator` is used to validate a range of numbers, not the range in the length of strings. – Oded Jun 21 '11 at 12:48

4 Answers4

13

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

Muhammad Akhtar
  • 51,913
  • 37
  • 138
  • 191
  • Would changing the type to integer, help the user in validating the length of string? – Hasan Fahim Jun 21 '11 at 13:19
  • 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. – Rudolf Dvoracek Sep 14 '12 at 14:32
  • 2
    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. – jsumrall Oct 09 '13 at 19:30
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;
    }
}

Hasan Fahim
  • 3,875
  • 1
  • 30
  • 51
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.

Akram Shahda
  • 14,655
  • 4
  • 45
  • 65
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>
Zia Khan
  • 188
  • 2
  • 9