Search code examples
javascripthtmlsrc

Why is my HTML file unable to use the JavaScript file that I have linked?


JavaScript file is not used in the HTML file despite linking it

I am unable to use the JavaScript file and validate my HTML form. I am wondering if the issue is the linking of the src directory is wrong or could it be that I am missing something in my JavaScript code.

File Directory Image

<html>

<head>
  <title>Registration Page</title>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="js/validation.js" type="text/javascript">
  </script>
</head>

<body>
  <form action="validate" method="post" name="register">
    Full Name: <input type="text" name="name" required/><br/> Email Address: <input type="email" name="email" required/><br/> Address Line 1: <input type="text" name="address1" required/><br/> Address Line 2: <input type="text" name="address2" /><br/>    Postal Code: <input type="number" name="postal" required/><br/> Mobile Number: <input type="number" name="mobile" required/><br/> Password: <input type="password" name="password" required/><br/> Confirm Password: <input type="password" name="cfpassword"
      required/><br/>
    <input type="submit" value="Submit" />
  </form>
</body>

</html>
function validateForm() {

  //Use a regular expression to check for the pattern of the password
  var regexPass = "^[0-9]{6}[a-zA-Z]{1}$";
  var regexMobile = "^[0-9]{8}$";
  var regexPost = "^[0-9]{6}$";
  //Retrieve the VALUE from the "password" field found in the "register" form
  var password1 = document.forms["register"]["password"].value;
  var password2 = document.forms["register"]["cfpassword"].value;
  var postalcode = document.forms["register"]["postal"].value;

  if (matchPost === null) {
    alert("The postal code given in the correct format. Please ensure 
      that is contains exactly 6 digits.
      ");

      // Return false to tell the form NOT to proceed to the servlet
      return false;
    }
    if (matchMobile === null) {
      alert("The mobile number given in the correct format. Please ensure 
        that is contains exactly 8 digits.
        ");

        // Return false to tell the form NOT to proceed to the servlet
        return false;
      }

      // If password not entered 
      if (password1 == '')
        alert("Please enter Password");

      // If confirm password not entered 
      else if (password2 == '')
        alert("Please enter confirm password");

      // If Not same return False.     
      else if (password1 != password2) {
        alert("\nPassword did not match: Please try again...")
        return false;
      }

      // If same return True. 
      else {
        return true
      }


    }

Solution

  • If your JS folder is in the same directory as your html file this code should work. Write a simple alert('ahoy') function in your JS file and reload your html to verify if your JS file is loaded or not.