0

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.

Mark Schultheiss
  • 28,892
  • 9
  • 63
  • 88
  • The code you've posted works fine (though you should compare to an empty string "") - can you please post the code that fails? – obscure Jun 15 '19 at 14:42
  • That's odd because whenever i attempt to submit the form it fails to validate and lets through empty results – Jamanator666 Jun 15 '19 at 14:45
  • Do you get any error in the console? – obscure Jun 15 '19 at 14:45
  • Using the chrome console i don't get any errors at all – Jamanator666 Jun 15 '19 at 14:50
  • This is likely something to do with posting to `action="OrderConfirmed.htm"` but we really cannot clearly tell here. I deleted my answer as it really did not address that. – Mark Schultheiss Jun 15 '19 at 14:51
  • If I click 'run code snippet' with your sample above I get both alert windows just fine. – obscure Jun 15 '19 at 14:53
  • Works for me in fiddle although value is set to " ", with a space initially, and you are comparing to " " in the function. So if you submit an empty value subsequently your validator will pass that through and submit the form, probably not the desired behavior. You might look at this also regarding accessing form elements: https://stackoverflow.com/questions/2435525/best-practice-access-form-elements-by-html-id-or-name-attribute – SScotti Jun 15 '19 at 15:04
  • i managed to implement the anser that was sent before and it seems to work sometimes then refuses to work then it works again. also the only error console will give me is that is this one: Failed to load resource: the server responded with a status of 400 () js:1 Access to XMLHttpRequest at 'https://gc.kis.v2.scr.kaspersky-labs.com/37ADCD39-E8FD-EC4B-9B87-989307ED7D40/init?url=https%3A%2F%2Fstacksnippets.net%2Fjs&isTopLevel=false&nocache=1f60e' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. – Jamanator666 Jun 15 '19 at 15:07
  • May I suggest using value.trim() and then simply seeing if anything exists, rather than checking for a blank space. – Scottux Jun 15 '19 at 15:07

1 Answers1

1

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>
kodvin
  • 1,128
  • 8
  • 14
  • No worries, though your code should work. Maybe there is something with including your script. – kodvin Jun 15 '19 at 15:34