There can be different ways to block non-numeric entries, some widely used can be
a) regular expressions
b) check for each character and match for numeric value
c) Determine and block the keys based on keypress event.
You can use the below two examples to test the above (a & c points), copy and paste the code below in a notepad, and save it as .htm. Do let me know if you find this post useful.
Test for Numeral using regular expression
------------------------------------------
<HTML><HEAD>
<TITLE>Test for Numeral using regular expression</TITLE>
<SCRIPT>
function isValidNumber(str)
{
var sValue;
sValue = str;
var decimalRE = "^(\\+|-)?[0-9][0-9]*(\\.[0-9]*)?$";
if (!(sValue.match(decimalRE) != null))
{
alert("Only valid numbers are allowed.");
return false;
}
return true;
}
</SCRIPT>
</HEAD>
<BODY>
Please
enter a value: <INPUT id=txt><BR><INPUT id=btn onclick="return
isValidNumber(document.getElementById('txt').value )" type=button value="Check
Numeric">
</BODY>
</HTML>
Test for Numeral using keycodes on keypress event
-------------------------------------------------
<HTML><HEAD>
<TITLE>Validate numerals on keypres</TITLE>
<SCRIPT>
function NumValidateDecimal(obj)
{
if((window.event.keyCode>=48 &&
window.event.keyCode<=57)|| window.event.keyCode==46 )
{
if(window.event.keyCode==46)
{
var strVal=String(obj.value);
var myRegExp=/\./;
var resIndex=strVal.search(myRegExp);
if(resIndex!=-1)
return false;
}
if(window.event.keyCode==45)
{
var strVal=String(obj.value);
var myRegExp=/\-/;
var resIndex=strVal.search(myRegExp);
if(resIndex==-1)
obj.value="-"+obj.value;
return false;
}
}
else
return false;
}
</SCRIPT>
</HEAD>
<BODY>
Please
enter a value: <INPUT onkeypress="return NumValidateDecimal(this)" id=txt>
</BODY></HTML>
Regards
Mike
Don't expect too much, too soon.
|