Disable a Button if non numeric characters are entered

Here's a scenario. You have to accept only numeric characters from the user in a textbox. If the user types in anything other than a numeric character, then the submit button should be disabled.

To achieve this requirement we can use JavaScript and the OnKeyUp event as shown below:


<head runat="server">


<script type="text/javascript">

function CallScript(sender, btn) {

var chkDigit = /^\d+$/;

if (chkDigit.test(sender.value)) {

document.getElementById(btn).disabled = false;


else {

document.getElementById(btn).disabled = true;






<form id="form1" runat="server">


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

<asp:Button ID="Button1" runat="server"

Text="Submit" Enabled="false" />





To register the OnKeyUp with the TextBox use the following code:


protected void Page_Load(object sender, EventArgs e)


TextBox1.Attributes.Add("onKeyUp", "CallScript(this,'Button1')");



Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)

TextBox1.Attributes.Add("onKeyUp", "CallScript(this,'Button1')")

End Sub

If you are using this script in a MasterPage, make sure to use Button1.ClientID

Note: Watch for the Copy and Paste scenarios where you will need to use the TextChangedEvent.

Will you give this article a +1 ? Thanks in advance

About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

No comments: