Click to See Complete Forum and Search --> : Validation


Webskater
08-05-2003, 06:08 AM
Can anyone tell me the code for looping through a form and checking if any of the fields are empty and, if they are, putting up an alert box saying 'You have not completed all the fields' and putting the focus on the first control with no data in it.
Thanks for any help.

Charles
08-05-2003, 06:27 AM
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="Content-Script-Type" content="text/javascript">
<title>Example</title>
<style type="text/css">
<!--
label {display:block; margin:1em 0em}
input {display:block}
-->
</style>
<script type="text/javascript">
<!--
function validate(f) {
var i;
for (i=0; i<f.elements.length; i++) {if (/^\s*$/.test(f.elements[i].value)) {
alert ('You have not completed all the fields.');
f.elements[i].focus();
return false;
}}
}
// -->
</script>
<form action="" onsubmit="return validate(this)">
<div>
<label>Fee<input type="text"></label>
<label>Fie<input type="text"></label>
<label>Foe<input type="text"></label>
<label>Fum<input type="text"></label>
<button type="submit">Submit</button>
</div>
</form>

Webskater
08-05-2003, 06:30 AM
Thanks very much.