BeanSoftware Logo

ASP.NET Database Search Control

    Write For Us

How To Allow Only Numbers In TextBox Control?

Very often developers need to allow only numbers in TextBox control. It can be very easily archived with markup code bellow:

<asp:TextBox id="txtNumbersOnly" Runat="server" />
<asp:RegularExpressionValidator  Runat="server" ID="valNumbersOnly" ControlToValidate="txtNumbersOnly" Display="Dynamic" ErrorMessage="Please enter a numbers only in text box." ValidationExpression="(^([0-9]*|\d*\d{1}?\d*)$)">


You still need to check user input on server side, because malicious user can make POST request without using your web form. You can perform this check by using Regex class. For this case, code would be:

[ C# ]

if (!Regex.IsMatch(txtNumbersOnly.Text,
    // It is not a number, do something!

[ VB.NET ]

If Not Regex.IsMatch(txtNumbersOnly.Text, _
       "^[a-zA-Z'.]{1,40}$") Then
   ' It is not a number, do something!
End If

Related articles:

1. Security Features in ASP.NET 2.0
2. Save & Read Image From Database

FAQ toolbar: Submit FAQ  |  Tell A Friend  |  Add to favorites  |  Feedback

Copyright © 2002-2008 Bean Software. All rights reserved.