Validate Login Page Using JavaScript

Having a login page made in HTML alone is not enough without form validation. Validating form makes your visitor life easier by knowing which of the element are lacking some information.

There are so many advantage of validating a form.

  • Avoid additional load on your web server
  • Avoid typing information repeatedly
  • Avoid page reload
  • Avoid inconsistent value like email address

The only problem with JavaScript validation is if the user disabled the JavaScript support on their browser. If this is the case, you need to make sure that you are also validating the form in server-side. In this case, no invalid information will pass to your database.

The code below is useful on our previous tutorial on “How to Create Secure Login Page in PHP/MySQL

Here's the code for our login form with JavaScript validation:

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  5. <title>Form Validation</title>
  6. <script type="text/javascript">
  7. function validateForm()
  8. {
  9. var user=document.login.username.value;
  10. var user=user.trim();
  11. var pass=document.login.password.value;
  12.  
  13. if(user == '')
  14. {
  15. document.getElementById('error').innerHTML="Please Enter Username";
  16. return false;
  17. }
  18.  
  19. if(pass == '')
  20. {
  21. document.getElementById('error').innerHTML="Please Enter Password";
  22. return false;
  23. }
  24. }
  25. </script>
  26. </head>
  27. <body>
  28. <form id="login" name="login" method="post" action="login.php" onsubmit="return validateForm()">
  29. <table width="510" border="0" align="center">
  30. <tr>
  31. <td>Login Form</td>
  32. <td><div id="error"></div></td>
  33. </tr>
  34. <tr>
  35. <td>Username:</td>
  36. <td><input type="text" name="username" id="username" /></td>
  37. </tr>
  38. <tr>
  39. <td>Password</td>
  40. <td><input type="password" name="password" id="password" /></td>
  41. </tr>
  42. <tr>
  43. <td>&nbsp;</td>
  44. <td><input type="submit" name="button" id="button" value="Submit" /></td>
  45. </tr>
  46. </table>
  47. </form>
  48. </body>
  49. </html>

Add new comment