Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<!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>

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading