Using RegularExpressionValidator for numbers only in textbox
Visual Studio 2012,ASP.NET,Web窗体。试图控制文本框中的输入,仅限数字。我有以下代码:
1 2 3 4 5 6 7 | <asp:RegularExpressionValidator id="RegularExpressionValidator1" ControlToValidate="txtAcres" ValidationExpression="^\d+" Display="Static" ErrorMessage="Only Numbers" EnableClientScript="False" runat="server"></asp:RegularExpressionValidator> |
但我可以输入任何文本。我错过了什么?
这首先检查文本框是否为空,然后只检查数字。
1 | </asp:TextBox> |
检查文本框是否为空:
1 | </asp:RequiredFieldValidator> |
仅允许数字:
1 | </asp:RegularExpressionValidator> |
您可以在ASPX页面上使用此代码。在validationExpression属性中使用
1 2 | <asp:RegularExpressionValidator runat="server" ErrorMessage="Numeric Only" ControlToValidate="txtstock" ValidationExpression="^[1-9]\d$"></asp:RegularExpressionValidator> |
您需要为
1 | 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
你可以使用