...

View Full Version : simple form validation, please tell me what i'm doing wrong



coder_seth
05-05-2004, 08:51 PM
it's running the function, because if i put an alert as the first statement, it will alert me. however the if condition is somenow not being met, or my DOM access is incorrect.. i dunno.. either way, the form will go through with no data, sending an empty email.



<script type="text/javascript">
function validate_contact() {
var contact = document.getElementById("contact");
if (contact.comments.value == "") {
alert("Comments are required.");
return false;
}
}
</script>




<form id="contact" method="post" action="contact.cfm">
<fieldset>
<label for="name">Name:</label>
<input type="text" name="name" id="name" />
<label for="email">Email:</label>
<input type="text" name="email" id="email" />
<label for="phone">Phone:</label>
<input type="text" name="phone" id="phone" />
</fieldset>
<fieldset>
<label for="comments" id="comments_label">Comments:</label>
<textarea name="comments" id="comments" rows="5" cols=""></textarea>
</fieldset>
<fieldset>
<input type="submit" name="submit" id="submit" value="Send" class="button" onclick="return validate_contact()" />
<input type="reset" name="reset" id="reset" value="Clear" class="button" />
<input type="hidden" name="submitted" value="yes" />
</fieldset>
</form>

sad69
05-05-2004, 09:30 PM
Why do you go through the form, why not access the textarea directly?



<script type="text/javascript">
function validate_contact() {
var comments = document.getElementById("comments");
if (comments.value == "") {
alert("Comments are required.");
return false;
}
}
</script>


But maybe you have some reason for doing it that way? I don't know that you can just do that: formName.formElement, especially because your inputs aren't directly beneath the form, they're within a fieldset. Perhaps if you gave an id to the fieldset, you could do something like fieldsetId.comments? or even contact.fieldsetId.comments?

Let me know, as I'd be curious to your solution.

Sadiq.

Roy Sinclair
05-05-2004, 09:56 PM
I put your code into a simple page and it works just fine in both IE 6 and Firefox.

Are you sure that no other part of the page that you didn't post isn't interfering somehow?

coder_seth
05-05-2004, 10:01 PM
well, i guess something MUST be interfering, because it's such a simple script, and i use essentially the same thing on my site and it works. :mad:

*edit: well, i switched it to access comments directly, and that works. *shrug* thanks.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum