...

View Full Version : Trouble with multiple validation forms



DannyJS1
09-03-2011, 08:36 PM
Hello, I'm trying to make a simple webpage with two input text boxes that when submitted when empty, I'll get an error pop-up telling me which ones are empty, both, first name, or last name. When there's only one if, the script works. But when there's multiple else ifs, nothing happens if I press submit. Can someone help me?


<html>
<head>
<script type="text/javascript">
function validateForm()
{
var x=document.forms["myForm"]["firstname"].value;
var y=document.forms["myForm"]["lastname"].value;
if (x==null || x=="" && y==null || y=="")
{
alert("Please put in your first and last name.");
return false;
}
else if (x==null || x=="")
{
alert("Please put in your first name.");
return false;
}
else if (y==null || y=="")
{
alert("Please put in your last name.");
return false:
}
}
</script>
</head>

<body>
<form name="myForm">
First name: <input type="text" name="firstname"><br>
Last name: <input type="text" name="lastname">
<input type="submit" value="Submit" onclick="validateForm()">
</form>
</body>

</html>

Philip M
09-04-2011, 12:01 PM
Several errors, now corrected:-


<html>
<head>
<script type="text/javascript">
function validateForm() {
var x=document.forms["myForm"]["firstname"].value;
var y=document.forms["myForm"]["lastname"].value;
if ((x==null || x=="") && (y==null || y=="")) {
alert("Please put in your first and last name.");
return false;
}
else if (x==null || x=="") {
alert("Please put in your first name.");
return false;
}
else if (y==null || y=="") {
alert("Please put in your last name.");
return false;
}
}
</script>
</head>

<body>
<form name="myForm">
First name: <input type="text" name="firstname"><br>
Last name: <input type="text" name="lastname">
<input type="submit" value="Submit" onclick="return validateForm()">
</form>
</body>

</html>



You should note that form validation of the pattern if (document.forms[0].elements[1].value == "") is barely worthy of the name, and virtually useless, as even a single space, an X or a ? will return false, that is pass the validation. This topic has been covered many times before in this forum.


Remove cap and push up bottom - Instructions on shaving stick



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum