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

Form Validation - using form name as variable

Status
Not open for further replies.

webRAD

Programmer
Oct 13, 2002
8
AU
Can someone please tell me why this form validation code is not working.

...

<Form name=&quot;theform&quot; method=&quot;post&quot; onSubmit=&quot;return ValidateRequiredField('theform', 'thefield', 'Works!!')&quot; action=&quot;test2.html&quot;>
<Input type=&quot;text&quot; name=&quot;thefield&quot; size=&quot;20&quot;>
<input type=&quot;submit&quot; value = &quot;send me info&quot;>
</form>
...

<Script Language=&quot;JavaScript&quot;>
<!--
function ValidateRequiredField(formName, fieldName, message)
{
if (document.formName.fieldName.value.length < 1)
alert(message);
return false;
}
</script>


For some reason I have to pass form name, field name and message as variables. Is this the right way I am coding.
If I specify form name and field name in the code it works fine. The code below works fine:

function ValidateRequiredField()
{
if (document.theform.thefield.value.length < 1)
alert('hey this works');
return false;
}

Thanks in advance.
 
Here is why it doesnt work.

The argument 'theForm' is a string. Right we know that.
The variable in the function definition formName is a reference to 'theForm'. OK, so what?

So document.formName becomes document.'theForm'. If this means anything, it means the string 'theForm' in the document. Which of course is not what we want, we want to refer to the form and its fields.

Now you could do this-
Code:
var vForm = eval(&quot;document.&quot; + formName);
The eval function processes the string created in the parentheses and then interprets that as a javascript statement. The result is that vForm refers to document.theForm which is what you are after.

But the real answer is to use the keyword this as an argument when you call the validation function like so-
Code:
onSubmit=&quot;return ValidateRequiredField(this.thefield, 'Works!!')&quot;
and refer to that field in the function like so-

Code:
function ValidateRequiredField(vField, messsage){
   if (vField.value.length < 1){
      alert(message);
      return false;
   }
   return true;
}

Note also the additional braces and return statement.
 
Thanks a lot for your reply. The solution works fine.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top