Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 463
KFP Avatar asked Apr 30 '13 17:04

KFP


3 Answers

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>
like image 164
Apollo Avatar answered Oct 04 '22 05:10

Apollo


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>
like image 25
TechnicalKalsa Avatar answered Oct 04 '22 07:10

TechnicalKalsa


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

like image 31
Adil Avatar answered Oct 04 '22 07:10

Adil