1

I have applied RangeValidator on TextBox. But it always shows me error : Invalid Range, though I have given minimum value 10 and maximum value 25. I want that user must not enter value whose length is less than 10 and greater than 25. I want that user can enter anything, so I have type="string" in RangeValidator. But it always gives me error message : Invalid Range.

<td>
    <asp:TextBox ID="tbPassword" runat="server" MaxLength="25" type="password">
    </asp:TextBox>
    <asp:RequiredFieldValidator ID="rfvPassword" runat="server" 
        ControlToValidate="tbPassword" ForeColor="red" Display="Dynamic" 
        ErrorMessage="Password is required." SetFocusOnError="true">
    </asp:RequiredFieldValidator>
    <asp:RangeValidator ID="rvPassword" ControlToValidate="tbPassword" 
        ForeColor="red" Display="Dynamic" MinimumValue="10" MaximumValue="25" 
        SetFocusOnError="true" Type="String" runat="server" 
        ErrorMessage="Invalid Range">
    </asp:RangeValidator>
</td>
Devraj Gadhavi
  • 3,541
  • 3
  • 38
  • 67
Afnan Ahmad
  • 2,492
  • 4
  • 24
  • 44

3 Answers3

7

For this you will need to use a CustomValidator control as suggested by Emad Mokhtar.

For server side validation, create an event like this.

protected void TextValidate(object source, ServerValidateEventArgs e)
{
    e.IsValid = (e.Value.Length >= 10 && e.value.Length <= 25);
}

For client side validation, create a javascript function like this.

<script type="text/javascript">
    function validateLength(oSrc, args){
        args.IsValid = (args.Value.length >= 10 && args.Value.length <= 25);
    }
</script>

Then in your aspx markup have the CustomValidator control like this.

<asp:Textbox id="tbPassword" runat="server" text=""></asp:Textbox>
<asp:CustomValidator id="customValidator" runat="server" 
    ControlToValidate = "tbPassword"
    OnServerValidate="TextValidate"
    ErrorMessage = "Password must be between 10 to 25 characters!"
    ClientValidationFunction="validateLength" >
</asp:CustomValidator>

You can find more details here.

Devraj Gadhavi
  • 3,541
  • 3
  • 38
  • 67
1

This validation can be implemented Using CustomValidator Control and apply your client and sever side validation, please find sample here.

Emad Mokhtar
  • 3,237
  • 5
  • 31
  • 49
  • i have just tried that but whn user enters value , valid or invalid , it does not show any error and goes in butSave_Click code behind much strange – Afnan Ahmad Jan 09 '14 at 19:46
0

I recently observed this cool feature, just use below attributes to asp control/html. minLength="10" maxLength="1000"

as the attributes clearly states it allows minimum of 10 characters and maximum of 1000 characters.

rANth
  • 397
  • 2
  • 7
  • 18