Check if character is numeric
I've written a client-side validation function (for a textbox) that checks if the key pressed by the user is numeric. I cannot get it to work properly, however. The following code does not prevent the user from entering a non-numeric character, but it does prevent the user from entering two non-numeric characters. For example if the user enters a "1" and the a "d", the textbox will display "1d". The next time the user presses a key, the "d" is removed and whatever character the user pressed replaces the "d". I don't want the textbox to display the character unless it is numeric.
'The following is entered in the codebehind
Code:
Dim txtQuantity As TextBox = e.Item.Cells(4).FindControl("txtQuantity")
txtQuantity.Attributes.Add("onkeypress", "IsNumeric(" & txtQuantity.ClientID & ",'Integer')")
'this is the javascript function called when the textbox's onkeypress event is fired
Code:
function IsNumeric(TextBox,strType)
// check for valid numeric strings
{
if (strType="Decimal")
{
var strValidChars = "0123456789.";
}
else if (strType="Integer")
{
var strValidChars = "0123456789";
}
var strString;
var strChar;
strString=TextBox.value;
for (i = 0; i < strString.length; i++)
{
strChar = strString.charAt(i);
if (strValidChars.indexOf(strChar) == -1)
{
TextBox.value = TextBox.value.substring(0, i);
TextBox.value.length = i
event.returnValue = false;
}
}
}
I'm not very proficient in Javascript so I'd appreciate any suggestions.