Forum Moderators: open
<script type="text/javascript"><!--
function validateForm() {
if (document.myform.name_1.value=="") {
alert("You did not fill our your first name.");
return false;
}
if (document.myform.name_2.value=="") {
alert("You did not fill our your last name.");
return false;
}else {return true; }
}
//-->
</script>
Here is my submit blurb
<td><input onClick="validateForm()" maxlength="2147483647" size="20" type="submit" value="Submit" /></td>
[edited by: ajohnson at 8:45 pm (utc) on June 27, 2008]
Returning false stops the browser from performing it's normal action. Since your Javascript manages the submit, there's never any need to return true.
Note the use of form as a variable in the rewritten function and this in the form tag. This passes a reference to the form object to the function.
<script type="text/javascript">
function validateForm(form) {
var msg = '';
if (form.name_1.value=="") {
msg = "You did not fill our your first name.\n";
}
if (form.name_2.value=="") {
msg += "You did not fill our your last name.\n";
}
if (msg != '') { alert(msg); }
else { form.submit(); }
return false;
}
</script>
<form name="myform" id="myWebForm" action="....." onSubmit="return validateForm(this);">
<input type="submit" value="Submit" />
Note also that by moving the action from the button to the onSubmit of the form, this will work if the user presses ENTER instead of clicking submit.
Aside: what's with that maxlength? That's over two billion characters . . . but you don't need maxlength or size on a submit button.
<script type="text/javascript"><!--
function validateForm() {
var msg = '';
if (bntform.name_1.value=="") {
msg = "You did not fill our your first name.\n";
}
....
if (msg != '') { alert(msg); }
else { form.submit(); }
return false;
}
</script>
<form id="myWebForm" action="https://www.example.net/account4/webform/" accept-charset="UNKNOWN" enctype="application/x-www-form-urlencoded" method="post" onSubmit="return validateForm(this);">
does not validate, and submits either way...
Review these two parts:
<form onSubmit="return validateForm(this);">
What you are doing is passing a reference to the current form as a parameter. Then in your script,
function validateForm() {
Nothing is accepting the parameter. I see you've changed "form" to "bntform" - all you should need is this:
function validateForm(bntform) {
var msg = '';
if (bntform.name_1.value=="") {
..........
A more robust solution in your other thread.