Using RegularExpressionValidator for numbers only in textbox

83,726

Solution 1

This checks first if textbox is blank and then it checks for numbers only.

<asp:TextBox ID="tbAccount" runat="server"></asp:TextBox>

Checks if textbox is blank:

<asp:RequiredFieldValidator ID="RequiredFieldValidatorAccount" runat="server" ErrorMessage="*Required" ControlToValidate="tbAccount" ForeColor="Red"></asp:RequiredFieldValidator>

Allows only numbers:

<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="tbAccount" ErrorMessage="Please Enter Only Numbers" ForeColor="Red" ValidationExpression="^\d+$"></asp:RegularExpressionValidator>

Solution 2

You can use this code on ASPX Page. Use ^[1-9]\d$ in ValidationExpression property.

<asp:TextBox runat="server" ID="txtstock" width="50" />
        <asp:RegularExpressionValidator runat="server" ErrorMessage="Numeric Only" ControlToValidate="txtstock"
      ValidationExpression="^[1-9]\d$"></asp:RegularExpressionValidator>

Solution 3

You need to set true for EnableClientScript property.

 EnableClientScript="true" 

Use the EnableClientScript property to specify whether client-side validation is enabled. Validation controls always perform validation on the server. They also have complete client-side implementation that allows DHTML-supported browsers (such as Microsoft Internet Explorer 4.0 and later) to perform validation on the client. Client-side validation enhances the validation process by checking user input before it is sent to the server. This allows errors to be detected on the client before the form is submitted, avoiding the round trip of information necessary for server-side validation, Reference

Share:
83,726
KFP
Author by

KFP

Updated on April 14, 2020

Comments

  • KFP
    KFP about 4 years

    Visual Studio 2012, Asp.net, webforms.
    Trying to control input into textbox, numbers only. I have the following code:

    <asp:RegularExpressionValidator id="RegularExpressionValidator1" 
                     ControlToValidate="txtAcres"
                     ValidationExpression="^\d+"
                     Display="Static"
                     ErrorMessage="Only Numbers"
                     EnableClientScript="False" 
                     runat="server"></asp:RegularExpressionValidator>
    

    but i am allowed to enter any text. What am I missing?