mandelbug
mandelbug

Reputation: 1798

Having trouble with Javascript. Haven't done this in a while

I'm trying to remember how to do this. I need to make two password fields and the passwords have to match. You check if they match by pressing a button. They have to have one uppercase and a number and be 4 characters long. If the passwords pass all that, you go onto another page.

so far I have

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
<script type="text/javascript">
function password()
{
var pwd1 = document.getElementsByName("pwd1").value;
var pwd2 = document.getElementsByName("pwd2").value;

if(pwd1 == pwd2)
{
window.location.href = '...';
}
else
{
Alert("Passwords do not match or your password is not longer than 4 characters");
}
}

</script>
</head>
<body>

<input type="password" name="pwd1"/>
<input type="password" name="pwd2"/>
<input type="button" onClick="password();" value="Submit" />


</body>
</html>

Upvotes: 0

Views: 101

Answers (2)

tez
tez

Reputation: 574

Alright so your password function should look something like this:

function password() {
  var pwd1 = document.getElementsByName("pwd1")[0].value
    , pwd2 = document.getElementsByName("pwd2")[0].value
    , rules = /(?=.*\d)(?=.*[A-Z])/;

  if(pwd1 === pwd2 && pwd1.length >= 4) {
    if(rules.test(pwd1)) {
      //  redirect them now
      //  window.location.href = ...
    } else {
      alert('Password must contain at least 1 Capital letter and 1 digit');
    }
  }
  else{
    alert('Passwords must match and be at least 4 characters');
  }
}

Upvotes: 2

alex
alex

Reputation: 490283

For the error condition...

(pwd1 != pwd2 || pwd1.length >= 4 || ! pwd1.match(/\d/) || ! pwd1.match(/[A-Z]/))

Also, alert() does not have a capital and your selecting of the elements needs to subscript ([0]) the first.

jsFiddle.

Upvotes: 2

Related Questions