I am using the following javascript for form validation:
<script type="text/javascript">
function validate_form ( )
{
valid = true;
if ( document.contact_form.contact_name.value == "" )
{
alert ( "Please fill in the 'Your Name' box." );
valid = false;
}
if ( ( document.contact_form.gender[0].checked == false ) && ( document.contact_form.gender[1].checked == false ) )
{
alert ( "Please choose your Gender: Male or Female" );
valid = false;
}
if ( document.contact_form.age.selectedIndex == 0 )
{
alert ( "Please select your Age." );
valid = false;
}
if ( document.contact_form.terms.checked == false )
{
alert ( "Please check the Terms & Conditions box." );
valid = false;
}
return valid;
}
</script>
The form:
<form name="contact_form" method="post" action="somepage.php" onSubmit="return validate_form();">
<h1>Please Enter Your Details Below</h1>
<p>Your Name: <input type="text" name="contact_name"></p>
<p>Your Gender: <input type="radio" name="gender" value="Male"> Male
<input type="radio" name="gender" value="Female"> Female</p>
<p>Your Age:
<select name="age">
<option value="">Please Select an Option:</option>
<option value="0-18 years">0-18 years</option>
<option value="18-30 years">18-30 years</option>
<option value="30-45 years">30-45 years</option>
<option value="45-60 years">45-60 years</option>
<option value="60+ years">60+ years</option>
</select>
<p>Do you agree to the Terms and Conditions?
<input type="checkbox" name="terms" value="Yes"> Yes
<p><input type="submit" name="send" value="Send Details"></p>
</form>
The validation works fine, except it displays one alert box after another to point out which fields haven’t been filled in or selected.
How can this script be modified so that all the missing fields are pointed out in ONE alert box like:
Please fill in the following fields:
Name, Gender, Age, Terms and
Conditions
Use a string or an array (as in the example below) to accumulate the error fields then generate the alert statement and return value based on its contents. For example: