PDA

View Full Version : Form validation malfunctioning - javascript



blor
05-16-2011, 05:24 AM
Dear Forum Members,

The aim is to validate so text inputs, selection list and radio button are filled, selected or checked.

otherwise alert.window should execute with a message.

The issue is that when onsubmit runs the form data posts and no alerts are triggered.

Please tell me where I went wrong.

Thank you.



function validate () {
if (document.forms[0].visitor_name.value == ""
|| document.forms[0].email.value == ""
|| document.forms[0].phone.value == "" ) {
window.alert("Please enter your information.");
return false;
}
else if (document.forms[0].propertyType.selectedIndex == -1)
{
window.alert("You must select a property type");
return false;
}
else
return true;
var contactHow = false;
if(document.forms[0].contactHow.checked == false){
window.alert("Please select a contact method.");
return false;
}
var contactMethod = false;
for (var i=0; i<3; i++) {
if (document.forms[0].contactHow[i].checked == true) {
contactMethod = true;
break;
}
}
if (contactHowSelected == false) {
window.alert("You must select a contact method.");
return false;
}
else
return true;
}
function confirmSubmit() {
var submitForm=window.confirm("Are you sure you want to submit the form?");
if(submitForm == true)
return true;
return false;
}

<form action="formProcessor.html" method="get" enctype="application/x-www-form-urlencoded">
<p>Name:<input type="text" name="visitor_name" value="Enter your name" size="50"
onclick="if (this.value =='Enter your name') this.value='';"/></p>
<p>E-mail:<input type="text" name="email" value="Enter your Email" size="50"
onclick="if (this.value =='Enter your Email') this.value='';"/></p>
<p>Phone:<input type="text" name="phone" value="Enter you phone number" size="50"
onclick="if (this.value =='Enter you phone number') this.value='';" /></p>

<p>Property <select name="propertyType">
<option value="unselected">Select a property Type</option>
<option value="condo">Condo</option>
<option value="duplex">Duplex</option>
<option value="house">House</option>
</select></p>

<p>How should we contact you?
<input type="radio" name="contactHow" value="call_me" />Call me
<input type="radio" name="contactHow" value="e-mail_me" />E-mail me
<input type="radio" name="contactHow" value="snail_mail" />Snail mail
</p>
<p><input type="submit" onsubmit="validate()" /></p>
</form>

jscheuer1
05-16-2011, 07:21 AM
There could be other problems. But the form is what submits, not the submit button. It only tells the form to submit. Also I see your validate function returns true or false, but that has to be communicated to the form at submission.

So, get rid of the highlighted here:


<p><input type="submit" onsubmit="validate()" /></p>

And add the highlighted here:


<form action="formProcessor.html" onsubmit="return validate();" method="get" enctype="application/x-www-form-urlencoded">

blor
05-19-2011, 04:13 PM
I appreciate you taking a look at it thank you.