| |||||||||||
Data Entry ValidationChecking for numeric entries onlyThe following is a sample validation routine that submits the form only when a text field does not contain letters or characters other than a positive floating-point number a number that can contain decimals. Now, let's see how this is done. Basically, there are two handlers that test the entry:
<script language="JavaScript">
<!--
function isDigit ( evt ) {
var keyCode = evt.which ? evt.which : evt.keyCode;
digit = !isNaN ( parseInt ( String.fromCharCode ( keyCode ) ) ) ||
( keyCode == 190 || keyCode == 110 ) ||
( keyCode >= 8 && keyCode <= 46 &&
keyCode !=16 && keyCode !=32 );
digit = ie4up ? digit || ( keyCode >= 96 && keyCode <=105 ) : digit;
return ( digit );
}
function validateNumber ( num ) {
var dot = 0;
for ( n=0; n < num.length; n ++ ) {
digit = num.charCodeAt ( n ) >=48 &&
num.charCodeAt ( n ) <=57 || num.charCodeAt ( n ) ==46;
if ( !digit ) {
alert ( 'No way, sorry.' );
theForm.theField.select ( );
return false;
}
if ( num.charCodeAt ( n ) == 46 ) {
dot ++ ;
if ( dot>1 ) {
alert ( 'Invalid decimals, sorry.' );
theForm.theField.select ( );
return false;
}
}
}
return true
}
//-->
</script>
<form name="theForm"
onsubmit="return validateNumber ( this.theField.value )">
<input name="theField" onkeydown="
if ( !isDigit ( event ) ) {
alert ( 'Oops! numbers only please.' );
return false;
}">
</form>
As the user types in a key, the function
The handler returns The keyCode values between When the form is submitted, the function This ensures that in cases wherein the text input accepts an invalid entry that is not trapped at the field-level, such as the entry having more than one decimal separator, the form-level handler will still invalidate the submission. Note, however, that the behavior of this validation routine has not been identified in cases of operating system and browser combinations that do not conform to the Unicode standard and may return non-standard keyCode values. See AlsoValidating Against a Data Type ( Web Forms ) Web Forms Validation |
| ||||||||||
Check out related books at Amazon
© 2000-2008 Rey Nuñez All rights reserved.
If you have any question, comment or suggestion
about this site, please send us a note
You can help support aspxtreme