home

Javascript Login Form Validation

In this class we will learn about javascript basic login form validation, now are day every application required, and this code is clear and understandable for every web newbies (beginner). To create for validation what and all other things we required, basic html form along with some form inputs like username and password to validate this element, Housley we need bunch of javascript code, in this first class I am going brief you about javascript code.

In this below code section have html form with name of loginform, and also, it has couple of inputs one is for Username and another one is for Password. Username input has some name called user_name and other one Password has a name called pass_word(password type is “password” to display value something like this ****** ), and last when is action(click) on button, javascript function will respond(login()).

<form  name="loginform" action="thanks.html">
  <input  type="text" name="user_name"/>
  <input  type="password" name="pass_word"/>
  <input  type="button" value="login"  onclick="login()"/>
</form>

Javascript Login Form Code

To validation our above html form what we need in first step, need a function called login(), the function is the main concept in javascript, its like container for entire application actions, lets go inside the function, in first line after declaration of function, also have two variables (user, pass) to store initial input values, after that we have other important concept called conditions.

<script>
  function login(){
        var user = document.loginform.user_name.value;
        var pass = document.loginform.pass_word.value;
  if(user == "" || pass == ""){
          alert("sorry...Please Enter Username and Passowrd");
     }else{
  if((user == "ustut" || user == "USTUT") && pass == "US@123"){
          document.loginform.submit();
    }else{
         alert("Please Enter Correct Credentials");
  }
       }
           }
</script>

Javscript conditions will works based on developer given rule, in this scenario if user is null (user == "" if user does not enter the username) or password is empty (pass == "" if user does not enter the pass) then alert condition will populate the alert values (“sorry...Please Enter Username and Passowrd”).

First of all, here we have three conditions what exactly happened with above conditions,