KFP
KFP

Reputation: 719

Using RegularExpressionValidator for numbers only in textbox

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?

Upvotes: 5

Views: 93512

Answers (4)

Apollo
Apollo

Reputation: 2070

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>

Upvotes: 14

Tran Anh Hien
Tran Anh Hien

Reputation: 757

You can use ^(0|[1-9]\d*)$ Good Sucessful !

Upvotes: 0

Kalu Singh Rao
Kalu Singh Rao

Reputation: 1697

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>

Upvotes: 4

Adil
Adil

Reputation: 148180

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

Upvotes: 2

Related Questions