JD88
JD88

Reputation: 51

Asp.net Validation. Only allow user to enter specific numbers in a text box

<asp:TextBox ID="Fund9" 
             runat="server" 
             columns="4" 
             MaxLength="3" Value="" /> 
<asp:RangeValidator ControlToValidate="Fund9" 
                    MinimumValue="100" 
                    MaximumValue="100" 
                    Type="Integer" 
                    ErrorMessage="Fund 9 must be 0 or 100" 
                    Text="Must be 100% if selected" runat="server" /></td></tr>

As you can see the validation on the above text box only allows the user to enter the number 100. I need it so the user can also enter 0 but no other options. I would appriciate some advice on this.

Upvotes: 2

Views: 2186

Answers (2)

Win
Win

Reputation: 62260

You can use RegularExpressionValidator. If it is required to enter, you can combine it with RequiredFieldValidator too.

<asp:TextBox ID="Fund9"
    runat="server"
    Columns="4"
    MaxLength="3" Value="" />
<asp:RegularExpressionValidator ID="Fund9RegularExpressionValidator"
    runat="server"
    ValidationExpression="^(0|100)$"
    ErrorMessage="Fund 9 must be 0 or 100" ControlToValidate="Fund9"
    Text="Must be 100% if selected" Display="Dynamic" />
<asp:Button runat="server" ID="SubmitButton" Text="Submit"
    OnClick="SubmitButton_Click" />

<%-- RequiredFieldValidator is optional --%>
<asp:RequiredFieldValidator ControlToValidate="Fund9" Text="Required"
    ErrorMessage="Required is required." runat="Server"
    ID="Fund9RequiredFieldValidator" Display="Dynamic" />

Upvotes: 3

Tim Schmelter
Tim Schmelter

Reputation: 460118

Use a CustomValidator

<asp:CustomValidator ID="ValidatFund" 
    ControlToValidate="Fund9" ValidateEmptyText="true"
    OnServerValidate="ValidateFund" runat="server"
    ErrorMessage="Fund 9 must be 0 or 100" >
</asp:CustomValidator>


protected void ValidateFund(Object sender, ServerValidateEventArgs e)
{
    e.IsValid = e.Value.Trim() == "0" || e.Value.Trim() == "100";
}

You can additionally provide a ClientValidationFunction in javascript.

Upvotes: 6

Related Questions