0

i'm trying to validate my html form but my JS script is not working, when i click submit button nothing happens except that my page is reload/refresh.

   var username = document.forms['forrm1']['name'];

  function Validate() {

    // validate username
     if (username.value == "") {
            username.style.border = "1px solid red";
            document.getElementById('nameErr').innerHTML = "Username is required";
            document.getElementById('nameErr').style.color = "red";
            username.focus();
           return false;}}

   </script>


 <form name="forrm1" method="post" action="#" onsubmit="return Validate()" >
        <div> Name <br><input type="text" name="name" id="name">
            <div Id="nameErr"></div></div><br>

        Email <br><input type="Email" name="email"> 
             <div id="emailErr"></div><br>

        Comment <br><textarea rows="5" cols="50" placeholder="type here ... ">
                    </textarea><br>

        <input type="submit" value="submit" ">

</form>
  • I suggest to put the `required` attribute on the input, like ``, this will check the input is not empty. Otherwise you can use also regular expression if you need to do something more complicate. (see https://www.w3schools.com/tags/att_input_pattern.asp) – Davide Bulbarelli Nov 16 '19 at 22:42

1 Answers1

0

Username is never set, therefore Validation is not reached :)

just move the line var username = document.forms['forrm1']['name']; into your function.

      <script>
      function Validate() {    
    //set it IN the Validate Function - then script works well :)
    var username = document.forms['forrm1']['name'];

   // validate username
    if (username.value == "") {
         username.style.border = "1px solid red";
         document.getElementById('nameErr').innerHTML = "Username is required";
         document.getElementById('nameErr').style.color = "red";

        username.focus();
        return false;}}

      </script>
mZed
  • 339
  • 2
  • 7