| |||||||||||
Data Entry ValidationCheck if all form fields are filled outThe FORM element has an onsubmit event which authors can use to call a form validation function that returns Typical validation routine is as follows: <form onsubmit="return validateForm ( this )" ...>
... form control definitions here ...
</form>
...
<script language="JavaSCript">
<!--
function validateForm ( form ) {
// check form fields and
// return false if not validated
// return true otherwise
}
//-->
</script>
The following example contains a generic function that may be used as a general handler for checking whether all the fields in a form have been filled out. When the submit button is clicked, the function loops through the form elements collection and checks for:
Of course such a validation may not be sufficient if you need to validate the type of input for text fields for example, only letters, numbers, dates, etc. but rather shows the basic routines to build upon. Now, let's explore the code. <script language="JavaScript">
<!--
function validateForm ( form ) {
for ( var e = 0; e < form.elements.length; e ++ ) {
var el = form.elements [ e ];
if ( el.type == 'text' || el.type == 'textarea' ||
el.type == 'password' || el.type == 'file' ) {
// check text fields
if ( el.value == '' ) {
alert ( 'Please fill out the ' + el.name + ' field' );
el.focus ( );
return false;
}
}
else if ( el.type.indexOf ( 'select' ) != -1 ) {
// check selectable dropdown menus
if ( el.selectedIndex == -1 ) {
alert ( 'Please select a value for ' + el.name );
el.focus ( );
return false;
}
}
else if ( el.type == 'radio' ) {
// check radio button groups
var group = form [ el.name ];
var checked = false;
if ( !group.length ) checked = el.checked;
else
for ( var r = 0; r < group.length; r ++ )
if ( ( checked = group [ r ].checked ) )
break;
if ( !checked ) {
alert ( 'Please check one of the ' +
el.name + ' buttons' );
el.focus ( );
return false;
}
}
else if ( el.type == 'checkbox' ) {
// check checkbox groups
var group = form [ el.name ];
if ( group.length ) {
var checked = false;
for ( var r = 0; r < group.length; r ++ )
if ( ( checked = group [ r ].checked ) )
break;
if ( !checked ) {
alert ( 'Please check one of the ' +
el.name + ' checkboxes' );
el.focus ( );
return false;
}
}
}
}
return true;
}
//-->
</script>
See AlsoValidating Required Entries ( 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