You must Sign In to post a response.

How to allow numeric characters on keypress event?


Are you looking for information on validation on key press event? Want to know how to allow numeric characters on key press event? Read this thread to learn more about validation on key press event with examples.

Hi,
I have a textbox for entering contact nos. which should accept only numeric values.
How to achieve this (with proper code explanation)?


Comments

Author: Danasegarane.A03 Sep 2013 Member Level: Gold   Points : 0

Refer :

http://stackoverflow.com/questions/469357/html-text-input-allow-only-numeric-input

Author: Danasegarane.A03 Sep 2013 Member Level: Gold   Points : 0

And this one

http://www.codeproject.com/Tips/328178/Allow-only-Numeric-values-in-ASP-Text-box-control

Author: Jivani04 Sep 2013 Member Level: Gold   Points : 2

private void textBox1_TextChanged(object sender, EventArgs e)
{
if (System.Text.RegularExpressions.Regex.IsMatch("[^0-9]", textBox1.Text))
{
MessageBox.Show("Please enter only numbers.");
textBox1.Text.Remove(textBox1.Text.Length - 1);
}
}

and another way to created:
void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if ( !char.IsDigit(e.KeyChar) )
{
e.Handled = true;
}
}

http://www.codeproject.com/Articles/220519/Numbers-or-Characters-only-Textbox-Validation-in-C

Author: Sumit Pyne04 Sep 2013 Member Level: Silver   Points : 2

You can use the following javascript code in the "onkeypress" event of the textbox.



function IsNumeric() {
var theEvent = window.event;
var key = theEvent.keyCode;
key = String.fromCharCode(key);

var regex = /[0-9]|\./;
if (!regex.test(key)) {
theEvent.returnValue = false;
if (theEvent.preventDefault) theEvent.preventDefault();
}
}



Regards,
Sumit