[Javascript] form validation function

Peter Brunone peter at brunone.com
Thu Jan 23 10:18:21 CST 2003


Cutter,

	The easiest way I've found to accomplish this is to establish a naming
convention based on field type (e.g. txtField1, selField3) so you can just
check the first three characters of the field name.

	I believe every major browser supports the .selectedIndex property, as well
as the .options collection... so merely accessing select values should be
pretty easy.  Discerning the type, then, should be easy as well, but for one
little problem.

	The following is a little script I whipped up to check the field type; for
some reason, though, once it encounters a SELECT in Netscape 4.79 (my NN4
version), all subsequent fields somehow have a length as well.  It works
fine in IE, as well as Netscape 6.2; anybody have a thought for old Netscape
4?

-Peter

<html>
<head>
	<title>Field Type Test</title>
<script language="javascript">
function checkForm() {
	var i = 0;

	for(i=0;i<document.myForm.elements.length;i++) {
		if(document.myForm.elements[i].options) {
		// You can use length instead of options
			alert(document.myForm.elements[i].name);
			}
		else {
			alert(document.myForm.elements[i].name + " has no length ");
			}
		}
	}
</script>
</head>
<body>
<form name="myForm">
<input type="text" name="myText">
<br><br>
<select name="mySelect">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<br><br>
<input type="text" name="myText2">
<br><br>
<input type="button" name="myButt" value="Check" onClick="checkForm();">
</form>
</body>
</html>



|-----Original Message-----
|From: javascript-admin at LaTech.edu [mailto:javascript-admin at LaTech.edu]On
|Behalf Of Cutter (JavaScript)
|Sent: Thursday, January 23, 2003 9:35 AM
|To: javascript at LaTech.edu
|Subject: [Javascript] form validation function
|
|
|I would like to write a form validation function where I pass the names
|of all of the fields to validate to the function, which then loops
|through the list to make sure that no field is empty and returns true.
|
|There's a little more to it, but that's the basics. My question is, is
|there a way to test if a field is an input or a select? Since accessing
|select values (especially cross browser) is not so straight forward I
|will need to plan for this contingency. Any suggestions?
|
|Cutter
|




More information about the Javascript mailing list