Home > Abakada: Back to Basics > Basic Scripting > Data Entry Validation > Check if all form fields are filled out
Abakada ~ Back to Basics
The FORM element has an onsubmit event which authors can use to call a form validation function that returns true
to allow submission if the input in the form is valid, and false
to cancel submission if the validation failed.
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:
- INPUT type text fields, passwords, file upload and TEXTAREA elements that they contain some input
- SELECT elements that at least one option is selected
- radio buttons/button groups that one is checked
- checkbox groups ( single checkboxes pass validation unchecked ) that at least one checkbox is checked
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>
Validating Required Entries ( Web Forms ) Web Forms Validation