JavaScript Required Field Validation on Web Form
From ClubsWiki
This script will check to see if the web user leaves any required fields blank, and if so, tell them which ones still need to be completed.
I was not satisfied with JavaScript Field Validation scripts I found online, so I wrote my own. I think it is easier to understand and adapt than others I have seen and will not break if you name your form, write a custom warning, or change the fieldnames to suit your purposes.
Code:
<HTML>
<HEAD>
<script language="JavaScript">
<!-- *** JAVASCRIPT FIELD VALIDATION BY STEVEN K. TAJIRI
function validate(something)
{
var warning = "Required fields : \n";
var same = warning;
if (something.field1.value=="") { warning += " ** field1 \n"; }
if (something.field2.value=="") { warning += " ** field2 \n"; }
if (something.field3.value=="") { warning += " ** field3 \n"; }
if (something.field4.value=="") { warning += " ** field4 \n"; }
if (warning == same) { return true; }
else { alert(warning); return false; }
}
-->
</script>
</HEAD>
<BODY>
<form name="formname" action=" " onsubmit="return validate(this)">
Enter field1** : <input type="text" name="field1" size="12"><BR>
Enter field2** : <input type="text" name="field2" size="12"><BR>
Enter field3** : <input type="text" name="field3" size="12"><BR>
Enter field4** : <input type="text" name="field4" size="12"><BR>
** indicates a required field. <BR>
<BR>
<input type="submit" value="Submit">
</form>
</BODY>
</HTML>