Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Validating a form (easier step)

Validation via Arrays

Validating a form (easier step)

by  GUJUm0deL  Posted    (Edited  )
This idea came to me as a hunch. At my job I have to do alot validation of forms and I get tired to write the entire document.form.name.value and other forms of checking (like selected, etc...) so I thought "Hmmmm, can U use arrays??" and lo-and-behold here it is...
This works in IE and NS6 (not NS4, for some reason...it doesn't like the for loop)...you can use textboxes, select choices and radiobuttons, etc...all you have to do is make sure that all the form elements have the same id attribute name...
This is an example code...enjoy!! :)

<html>
<head>
<title>Validation via Arrays</title>
[color red]
<script>
function GUJUm0deL() {
//input the msg message here...just increment by one for more alerts...
var msg1 = "please answer 1";
var msg2 = "please answer 2";
var msg3 = "please answer 3";
var msg4 = "please answer 4";
var msg5 = "please answer 5";

//make sure the id=ONE is the same in all checks (id=ONE is defined in the <form> next to each form element...
for(i=0; i<=document.form1.ONE.length; i++) {
if(document.form1.ONE[0].value == "") {
alert(msg1);
return false;
}
if(document.form1.ONE[1].value == "") {
alert(msg2);
return false;
}
if(document.form1.ONE[2].value == "") {
alert(msg3);
return false;
}
if(document.form1.ONE[3].value == "") {
alert(msg4);
return false;
}
if(document.form1.ONE[4].options[0].selected == true) {
alert(msg5);
return false;
}
}
}
</script>[/color]
</head>

<body bgcolor="#FFFFFF" text="#000000">
<form name="form1" method="post" action="mailto:me@aol.com" [color green]onSubmit="return GUJUm0deL()"[/color]>
<p>
<input type="text" id="ONE" name="textfield">
</p>
<p>
<input type="text" id="ONE" name="textfield2">
</p>
<p>
<input type="text" id="ONE" name="textfield3">
</p>
<p>
<input type="text" id="ONE" name="textfield4">
</p>

<p>
<select id="ONE" name="select">
<option selected>Select One</option>
<option>One</option>
<option>Two</option>
<option>Three</option>
</select>
</p>
<p>
<input type="submit" name="Submit" value="Submit">
</p>
</form>
</body>
</html>
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top