Jamanator666
Jamanator666

Reputation: 3

Javascript validation for html form not working

I'm trying to make a working javascript validator for an HTML form for an assessment, I have gotten the lecturer to help me originally, however they could not solve the issue. The validation works until I add another input to validate then it completely stops working. I am new to javascript, i have never worked with it before.

I have tried rebuiling the validator and order form completely multiple times. I have reviewed the code multiple times to no avail.

function validateForm() {
  var x = document.forms["myForm"]["fname"].value;
  if (x == " ") {
    alert("Name must be filled out");
    return false;
  }
  var y = document.forms["myForm"]["mname"].value;
  if (y == " ") {
    alert("middle name must be filled out");
    return false;
  }
}
<script src="Validator.js"></script>
<form name="myForm" onsubmit="return validateForm()" action="OrderConfirmed.htm" method="post">
  Name: <input type="text" name="fname" value=" "> Middle Name: <input type="text" name="mname" value=" ">
  <input type="submit" value="Submit">
</form>

The expected result is that when the form is submitted but a field is empty a message (dialog box) should be displayed telling the user which input is not filled in.

Upvotes: 0

Views: 84

Answers (1)

kodvin
kodvin

Reputation: 1276

You could solve it by using 'event.preventDefault'. (But your code should work too...) Here is example code:

<html>
<head>
    </head>
    <body>
	<form name="myForm" onsubmit="validateForm(event)">
	    Name: <input type="text" name="fname" value=" ">
	    Middle Name: <input type="text" name="mname" value=" ">
	    <input type="submit" value="Submit">
	</form>
	<script type="text/javascript">
	    function validateForm(e) {
                var x = document.forms["myForm"]["fname"].value;
                if (x == " ") {
                    e.preventDefault();
                    alert("Name must be filled out");
                    return false;
                }
                var y = document.forms["myForm"]["mname"].value;
                if (y == " ") {
                    e.preventDefault();
                    alert("middle name must be filled out");
                    return false;
                }
            }
        </script>
     </body>
</html>

Upvotes: 1

Related Questions