MechroMancer
MechroMancer

Reputation: 1

Password validation won't work Javascript

Trying to get my page to take a password that is 8 or more characters length and contains a number and a letter, but its not working and I don't understand why. Once the password is valid, it takes the user to a success page.

CODE:

<script>
  $(document).ready(function() {
    $("#submit").click(function() {

      var name = document.getElementById("name").value;
      var email = document.getElementById("email").value;
      var password = document.getElementById("password").value;
      var confirm = document.getElementById("confirm").value;
      var valid = password.length >= 8 // at least 8 characters
                  && /[a-z]/.test(password) // contains a lowercase letter
                  && /\d/.test(password) // contains a digit


      var dataString = 'name=' + name + '&email=' + email + '&password=' + password;
      console.log(dataString);
      if (name == '' || email == '' || password == '') {
        alert("Fill in empty fields");
      }
      if (password != confirm) {
        alert("Passwords do not match.");
      } else if (password == confirm && password != valid) {
        alert("Password not valid.");
      } else if(password == '' && confirm == '' && password == confirm) {
        alert("password can't be empty");
      } else {
        alert("matched");
        window.location="newpage.html"
      }
      return false;
    });
  });
</script>

Please help me :(

Upvotes: 0

Views: 149

Answers (2)

JorgeObregon
JorgeObregon

Reputation: 3310

Instead of a huge function, break it into pieces (smaller functions). That way is easier to manage any error, bugs, maintenance etc.

Now, specifically answer your question on "password validation function", check this snippet.

(function($){ $(function(){
   
  var isPasswordValid = function(password){
    return password.length >= 8 
      && /[a-z]/.test(password)
      && /\d/.test(password)
  }
  
  console.log('Is "weakpwd" valid?', isPasswordValid('weakpwd'));
  
  console.log('Is "atLeastEightChars" valid?', isPasswordValid('atLeastEightChars'));
  
  console.log('Is "Gr3atPassword!" valid?', isPasswordValid('Gr3atPassword!'));
  
}) })(jQuery)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

I used the same checks you used for the password... and it's good! Which means the problem you're having is somewhere else, not in the password-checking step.

Cheers,

Upvotes: 0

Murali VP
Murali VP

Reputation: 6417

if(password == confirm && !valid)

should be that.

Upvotes: 1

Related Questions