-1

I would like to create a validation for my password and confirm password. I currently have it so that if they don't match, it will come up with an alert for the user and tell them that they don't match, however even if they dont match it still continues and sends the form data to the desired location. How can I get it to validate and if they aren't the same, it will ask again and again until the condition is met?

Here is my code.

<script>
function checkpassword()
    {
        var p = Register.pass.value;
        var cp = Register.cpass.value;
        if(p == cp)
            alert("Passwords match!")
        else if (p != cp) 
            alert("Passwords do not match!") 
    }
</script>
isherwood
  • 58,414
  • 16
  • 114
  • 157
Jonny
  • 23
  • 3

4 Answers4

0

You can do something like this:

function checkpassword() {
    var p = Register.pass.value;
    var cp = Register.cpass.value;
    if (p == cp) {
        alert("Passwords match!")
        return true;
    }

    alert("Passwords do not match!")
    return false;
}

And then in the part where you send the data:

if (checkpassword()) {
 // Send the data
} else {
 // Do nothing
}
Mark
  • 5,089
  • 2
  • 20
  • 31
0
    <form class="pure-form">
        <fieldset>
            <legend>Confirm password with HTML5</legend>

            <input type="password" placeholder="Password" id="password" required>
        <input type="password" placeholder="Confirm Password" id="confirm_password" required>

            <button type="submit" class="pure-button pure-button-primary">Confirm</button>
        </fieldset>
    </form>
    var password = document.getElementById("password")
      , confirm_password = document.getElementById("confirm_password");

    function validatePassword(){
      if(password.value != confirm_password.value) {
        confirm_password.setCustomValidity("Passwords Don't Match");
      } else {
        confirm_password.setCustomValidity('');
      }
    }
password.onchange = validatePassword;

confirm_password.onkeyup = validatePassword;
0

The issue is that you are only alerting if the password matches or not. Try returning true or false according to the criteria.

Example

function validateForm(){
    if(checkPassword()) form.submit();
}

function checkPassword(){
    var p=Register.pass.value;
    var cp=Register.cpass.value;
    if(p==cp) return true;
    else return false
}

Validate form can be called when you are submitting your form. Your code was okay but it missed return statement. Which would be used to either submit the form or not.

Farhan Qasim
  • 990
  • 5
  • 18
0

You mean you want a loop.Try this.

function checkpassword()
    {
    var wrong = true;
      while(wrong)
      {
        var p = Register.pass.value;
        var cp = Register.cpass.value;
        if(p == cp)
        {     
            wrong = false;
            alert("Passwords match!")
         }
        else if (p != cp) 
            alert("Passwords do not match!") 
       }
    }