Home > Software engineering >  How I can validate the form with another method like asynchronous methods(promises or async-await)?
How I can validate the form with another method like asynchronous methods(promises or async-await)?

Time:11-13

How I can validate the form below with another method like asynchronous methods(promises or async-await)?

In the form below, the form is validated if onsubmit ="return validateForm()" is equal to the boolean true and it is not validated if onsubmit ="return validateForm()" is equal to the boolean false.

My problem is : the asynchronous functions always return promises, and don't return boolean value...

<!DOCTYPE html>
<html>
   <head>
      <title>Hello Javascript</title>
      <script type = "text/javascript">
         function validateForm()  {
             var u = document.getElementById("username").value;
             var p = document.getElementById("password").value;

             if(u== "") {
                 alert("Please enter your Username");
                 return false;
             }
             if(p == "") {
                 alert("Please enter you Password");
                 return false;
             }

             alert("All datas are valid!, send it to the server!")

             return true;
         }
      </script>
   </head>
   <body>

      <h2>Enter your Username and Password</h2>

      <div style="border:1px solid #ddd; padding: 5px;">
         <form method="POST" action="process-action.html" onsubmit = "return validateForm()">
            Username: <input type="text" name="username" id="username"/>
            <br><br>
            Password: <input type="password" name = "password" id="password"/>
            <br><br>
            <button type="submit">Submit</button>
         </form>
      </div>

   </body>
</html>

CodePudding user response:

The validation code you wrote is synchronous client side code, and you don't need promises to execute it.

What you need to do here is use e.preventDefault because otherwise the submit button will try to trigger a form submit to the server.

Look at this answer as example.

If you take this road, use e.preventDefault to prevent triggering the form submit, validate the form and submit it by launching an ajax call instead.

  • Related