Hi all..

I need to restrict the user from entering any non numeric data in my text box present in an .aspx page.The user should able to enter only numeric values in the text box..Someone help in this regard with javascript..


Regards,
Balagurunathan S

Here is a quick and dirty way of doing it. It should suffice your purpose, but I must warn you that any kind of validation done at client side is moot, pointless. Validation at the server is what you must go for unless its an intranet application with limited target audience who can be absolutely trusted.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="generator" content="HTML Tidy for Linux/x86 (vers 1 September 2005), see www.w3.org" />
<title>sample page</title>
<script type="text/javascript">
//<![CDATA[
    function verify(frm)
    {
        var element = document.getElementById('txt');
        if(isNaN(new Number(element.value)))
                element.value = element.value.substring(0, element.value.length - 1) 
    }
//]]>
</script>
</head>
<body>
<form action=""><input type="text" onkeyup="verify(this.id);" name="txt" id="txt" /></form>
</body>
</html>

PS: This implementation allows spaces which shouldn't be a problem as such. If you still think you are going to have problems, just trim the value. Also this implementation is not the best of its kind. I can come up with an optimized implementation which uses events to detect which key has been pressed but its more pain in the neck than it's worth...

I use isNaN(variable) to check if the input is a valid number. If it is not, I return false, and the submit does not take place.

But remember that anyone can turn off JavaScript with their browser controls. With JavaScript off, the button works just as if you had no JS code.

This article has been dead for over six months. Start a new discussion instead.