0

I'm having problems getting my form to validate with Javascript. I've tried a bunch of different things, but I just can't get it to work. It's possible I'm missing something completely basic, I am pretty new at this. Please let me know what I could possibly change.

<!DOCTYPE html>

<html lang = "en">
<head>
 <title>  </title>
 <meta charset = "utf-8" />
 
</head>
<body>
 <script lang = "text/javascript">
 
 document.getElementById("myForm").onsubmit = validateForm();
 
 function zipcheck(sZip)
 {
  var postalRegex = /^d{5}(-\d{4})?$/;
  return postalRegex.test(sZip);
 }
 function validateForm()
 {
  if (zipcheck(document.getElementById("zip"))
   return true;
  else
  {
   alert(document.getElementById("zip") + " is not a valid zip code");
   return false;
  }
 }
 </script>
 <form id = "myForm" action = "" >
 <p>
 
 <label> Zip Code
  <input type = "text" id = "zip" />
 </label>
 
 <input type = "submit" name = "submit" />
 
 </p>
 </form>
 
</body>
</html>

1 Answers1

1

The Problem your are, checking the HTML Element not the Value. It should be document.getElementById("zip").value

    document.getElementById("myForm").onsubmit = validateForm;
 
 function zipcheck(sZip)
 {
  var postalRegex = /^d{5}(-\d{4})?$/;
  return postalRegex.test(sZip);
 }
  
 function validateForm()
 {
  if (zipcheck(document.getElementById("zip").value)){
   return true;
  }else
  {
   alert(document.getElementById("zip").value + " is not a valid zip code");
   return false;
  }
 }
<!DOCTYPE html>
<html lang = "en">
<head>
 <title>  </title>
 <meta charset = "utf-8" />
</head>
<body>
 <form id = "myForm" action="/test" method="get" >
 <p>
 <label> Zip Code
  <input type = "text" id = "zip"  />
 </label>
 <input type = "submit" name = "submit" />
 </p>
 </form>
</body>
</html>

here is a working sample on jsfiddler https://jsfiddle.net/u9suy516/

Optional Information: when using addEventListener you would also have to use the preventDefault() function on the passed event Parameter, but not need the return statments.

 function validateForm(event)
 {
    if (!zipcheck(document.getElementById("zip").value)) {
        alert(document.getElementById("zip").value + " is not a valid zip code");
        event.preventDefault();
    }
 }
winner_joiner
  • 12,173
  • 4
  • 36
  • 61