Question

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>
Was it helpful?

Solution

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.

OTHER TIPS

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

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top