kathleen55
kathleen55

Reputation: 341

username and password validation using javascript

I have this simple problem that I don't know what did I do wrong.

so I have this code:

    function validateForm() 
    {
        var validation = true;
        validation &= validateUsername();
        validation &= validatePassword();
        return validation? true:false;
    }

    function validateUsername()
    {
        var username = $('#username').val();

        if( username == "" )
        {
            alert("Login failed, Please enter your username");
            return false;
        }

        else if( username != "username" )
        {
            alert("Login failed, Username Incorrect");
            return false;
        }

        else
        {
            return true;
        }

    }

    function validatePassword()
    {

        var password = $('#pass').val();

        if(password != "password")
        {
            alert("Login failed, Password is incorrect");
            return false;
        }

        else if(password == "")
        {
            alert("Login failed, Please enter your password");
            return false;
        }

        else
        {
            return true;
        }
    }

If I enter no password it should alert that you should enter your password but instead that it is alerting password is incorrect. Why is it not going through all the if's I created?

Upvotes: 0

Views: 3235

Answers (1)

adeneo
adeneo

Reputation: 318162

You swap the conditions, and check for an empty string before you check for the correct password

function validatePassword() {

   var password = $('#pass').val();

   if(password == "") {
       alert("Login failed, Please enter your password");
       return false;
   } else if(password != "password") {
       alert("Login failed, Password is incorrect");
       return false;
   } else {
       return true;
   }
}

right now you're checking if it's not the correct password first, and as an empty string probably isn't the correct password, that matches before the check for an empty string.

Upvotes: 1

Related Questions