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 Shaun E on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Simple form validation

Status
Not open for further replies.

bizrat

Programmer
May 13, 2004
10
US
I know how to do form validation. I have many forms to validate. I am trying to write (borrow and change) a JS function that receives a string that is broken down and then verified. The string format is a1;a2|b1;b2|...

a1 = name of field to validate
a2 = Engligh words about field being validated.


When I run the following code, I get a runtime error and it says 'document.form.manuf_name' is null or not an object.

What am I doing wrong? Is there a better way to do this?


JS:

function verify( name_str ) {
var themessage = "You are required to complete the following fields: ";
var origmessage;
var name_arr = new Array();
name_arr = name_str.split('|');

origmessage = themessage;

for( i=0; i<name_arr.length; i++ ) {
curr = name_arr[ i ];
var curr_arr = new Array();

curr_arr = curr.split(';');

myval = eval( "document.form." + curr_arr[0] + ".value" );
if( myval == "" ) {
themessage = themessage + " - " + curr_arr[1];
}
}

//alert if fields are empty and cancel form submit
if ( themessage == origmessage ) {
document.form.submit();
} else {
alert(themessage);
return false;
}
}

HTML:
<table>
<form action="code.php" method="post" id="" name="" onsubmit="verify('manuf_name;Manufacturer Name')" >

<tr>
<td width="20%" bgcolor="silver">Name *</td>
<td width="20%"><input type="text" name="manuf_name" size="20" maxlength="40" value=" "></td>
</tr>
<tr>
<td width="20%" bgcolor="silver">Description</td>
<td width="20%"><input type="text" name="manuf_desc" size="30" maxlength="90" ></td>
</tr>
<tr align=center bgcolor="gray">
<td colspan=2>
<input type="submit" name="Submit" value="Add Manufacturer">
</td>
</tr>
/form>
 

You may as well remove the "id" and "name" tags from your form since you're not using them at all.

Your close form tag is missing the open "less-than" bracket, so your form is not complete.

You should not use "document.form.". Instead, use "document.forms[0]."

And using eval is shockingly slow. Suggest replacing this:

Code:
myval  = eval( "document.form." + curr_arr[0] + ".value" );

with this:

Code:
myval = document.forms[0][curr_arr[0]].value;

Hope this gives you some starting pointers,
Dan
 
Sorry about the cut/paste errors.

The replacement code did the trick.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top