75

I have a project in which I have to add a registration form and I want to to validate that the password and confirm fields are equal without clicking the register button.

If password and confirm password field will not match, then I also want to put an error message at side of confirm password field and disable registration button.

following is my html code..

<form id="form" name="form" method="post" action="registration.php"> 
    <label >username : 
<input name="username" id="username" type="text" /></label> <br>
    <label >password : 
<input name="password" id="password" type="password" /></label>     
    <label>confirm password:
<input type="password" name="confirm_password" id="confirm_password" />
    </label>
<label>
  <input type="submit" name="submit"  value="registration"  />
</label>

Is there any way to do this?

starball
  • 20,030
  • 7
  • 43
  • 238
ravi
  • 831
  • 2
  • 8
  • 9
  • possible duplicate of [HTML - Change\Update page contents without refreshing\reloading the page](http://stackoverflow.com/questions/3644585/html-change-update-page-contents-without-refreshing-reloading-the-page) – Amal Murali Feb 12 '14 at 11:59
  • 1
    There are many ways, where is your attempt? – A. Wolff Feb 12 '14 at 12:00

15 Answers15

123

We will be looking at two approaches to achieve this. With and without using jQuery.

1. Using jQuery

You need to add a keyup function to both of your password and confirm password fields. The reason being that the text equality should be checked even if the password field changes. Thanks @kdjernigan for pointing that out

In this way, when you type in the field you will know if the password is same or not:

$('#password, #confirm_password').on('keyup', function () {
  if ($('#password').val() == $('#confirm_password').val()) {
    $('#message').html('Matching').css('color', 'green');
  } else 
    $('#message').html('Not Matching').css('color', 'red');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>password :
  <input name="password" id="password" type="password" />
</label>
<br>
<label>confirm password:
  <input type="password" name="confirm_password" id="confirm_password" />
  <span id='message'></span>
</label>

and here is the fiddle: http://jsfiddle.net/aelor/F6sEv/325/

2. Without using jQuery

We will use the onkeyup event of javascript on both the fields to achieve the same effect.

var check = function() {
  if (document.getElementById('password').value ==
    document.getElementById('confirm_password').value) {
    document.getElementById('message').style.color = 'green';
    document.getElementById('message').innerHTML = 'matching';
  } else {
    document.getElementById('message').style.color = 'red';
    document.getElementById('message').innerHTML = 'not matching';
  }
}
<label>password :
  <input name="password" id="password" type="password" onkeyup='check();' />
</label>
<br>
<label>confirm password:
  <input type="password" name="confirm_password" id="confirm_password"  onkeyup='check();' /> 
  <span id='message'></span>
</label>

and here is the fiddle: http://jsfiddle.net/aelor/F6sEv/324/

Community
  • 1
  • 1
aelor
  • 10,892
  • 3
  • 32
  • 48
  • 1
    `$('#password, #confirm_password').on('keyup', function () { if ($('#password').val() == $('#confirm_password').val()) { $('#message').html('Matching').css('color', 'green'); } else $('#message').html('Not Matching').css('color', 'red'); });` is also another modification of the same code where it performs the check when each of the 2 password inputs are modified. How this helps is if they enter both matching, and then accidentally modify the password field or if they change the password field, it will update the matching status. http://jsfiddle.net/C3rMw/ – kdjernigan May 06 '14 at 16:54
  • Just a little change to your script to make it look better! Good answer though. Here is the fiddle for others' future references : http://jsfiddle.net/F6sEv/52/ – Abhishek Ghosh Apr 25 '15 at 20:04
  • @AbhishekGhosh is this fiddle working without useing any js libraries, strange ? – fresher Oct 07 '16 at 05:47
  • 1
    @PhpBeginner: It is basic Javascript.. It is not using an JS library :) – Abhishek Ghosh Oct 07 '16 at 22:43
  • @aelor : Not sure if others had the same issue. I entered password and then was entering 'ConfirmPassword' data - immediately 'Passwords match' is shown but when i completed entering 'ConfirmPassword' details 'Passwords not match' is shown. Even if i enter correct ConfrimPassword or not the message 'Passwords not match' is shown always. This is my first time of UI development. Hope everyone will correct me if i am wrong anywhere :) – user2014 Apr 16 '17 at 21:56
  • @user2014 Welcome to SO, have you created a fiddle of the same. It will be easier for us to debug – aelor Apr 17 '17 at 07:41
  • @user2014 your document ready should have `$("#password, #confirm_password").keyup(checkPasswordMatch);` https://jsfiddle.net/aelor/00azu88j/1/. I have provided the reason in my answer as well. The keyup should work both ways. So that if the the password field changes, then also the check happens – aelor Apr 18 '17 at 05:51
  • Thanks for clear explanation @aelor . Sadly now also i see 'Password not match' all the time. – user2014 Apr 19 '17 at 17:17
  • @user2014 I am not sure what is the exact problem, in my comment above, I have updated your fiddle itself. and its working fine – aelor Apr 20 '17 at 12:46
  • Works like a charm, I used the pure JavaScript one... Simple, Elegant, Functional & Effective. – Samuel Ramzan Jun 09 '19 at 05:57
  • if you guys taking a error or not expected result try change : else $('#message').html('Not Matching').css('color', 'red'); tobe : else { $('#message').html('Not Matching').css('color', 'red'); } – Dariswan Janweri P. Dec 16 '19 at 18:16
  • @DariswanJanweriP.For single lines the curly braces are not needed – aelor Dec 23 '19 at 12:49
  • Great solution! With Jquery to hide/show predefined error message --> $('#password, #confirmpassword').on('keyup', function () { if ($('#password').val() == $('#confirmpassword').val()) { $('#errormsg').hide(); } else $('#errormsg').show(); }); – Jonyx4 Jul 15 '21 at 20:49
  • Beautiful solution. – wibberding Apr 06 '22 at 15:56
28

Using Native setCustomValidity

Compare the password/confirm-password input values on their change event and setCustomValidity accordingly:

function onChange() {
  const password = document.querySelector('input[name=password]');
  const confirm = document.querySelector('input[name=confirm]');
  if (confirm.value === password.value) {
    confirm.setCustomValidity('');
  } else {
    confirm.setCustomValidity('Passwords do not match');
  }
}
<form>
  <label>Password: <input name="password" type="password" onChange="onChange()" /> </label><br />
  <label>Confirm : <input name="confirm"  type="password" onChange="onChange()" /> </label><br />
  <input type="submit" />
</form>
laggingreflex
  • 32,948
  • 35
  • 141
  • 196
19

If you don't want use jQuery:

function check_pass() {
    if (document.getElementById('password').value ==
            document.getElementById('confirm_password').value) {
        document.getElementById('submit').disabled = false;
    } else {
        document.getElementById('submit').disabled = true;
    }
}
<input type="password" name="password" id="password" onchange='check_pass();'/>
<input type="password" name="confirm_password" id="confirm_password" onchange='check_pass();'/>
<input type="submit" name="submit"  value="registration"  id="submit" disabled/>
Al.G.
  • 4,327
  • 6
  • 31
  • 56
rjhdby
  • 1,278
  • 13
  • 15
5

Solution Using jQuery

 <script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>

 <style>
    #form label{float:left; width:140px;}
    #error_msg{color:red; font-weight:bold;}
 </style>

 <script>
    $(document).ready(function(){
        var $submitBtn = $("#form input[type='submit']");
        var $passwordBox = $("#password");
        var $confirmBox = $("#confirm_password");
        var $errorMsg =  $('<span id="error_msg">Passwords do not match.</span>');

        // This is incase the user hits refresh - some browsers will maintain the disabled state of the button.
        $submitBtn.removeAttr("disabled");

        function checkMatchingPasswords(){
            if($confirmBox.val() != "" && $passwordBox.val != ""){
                if( $confirmBox.val() != $passwordBox.val() ){
                    $submitBtn.attr("disabled", "disabled");
                    $errorMsg.insertAfter($confirmBox);
                }
            }
        }

        function resetPasswordError(){
            $submitBtn.removeAttr("disabled");
            var $errorCont = $("#error_msg");
            if($errorCont.length > 0){
                $errorCont.remove();
            }  
        }


        $("#confirm_password, #password")
             .on("keydown", function(e){
                /* only check when the tab or enter keys are pressed
                 * to prevent the method from being called needlessly  */
                if(e.keyCode == 13 || e.keyCode == 9) {
                    checkMatchingPasswords();
                }
             })
             .on("blur", function(){                    
                // also check when the element looses focus (clicks somewhere else)
                checkMatchingPasswords();
            })
            .on("focus", function(){
                // reset the error message when they go to make a change
                resetPasswordError();
            })

    });
  </script>

And update your form accordingly:

<form id="form" name="form" method="post" action="registration.php"> 
    <label for="username">Username : </label>
    <input name="username" id="username" type="text" /></label><br/>

    <label for="password">Password :</label> 
    <input name="password" id="password" type="password" /><br/>

    <label for="confirm_password">Confirm Password:</label>
    <input type="password" name="confirm_password" id="confirm_password" /><br/>

    <input type="submit" name="submit"  value="registration"  />
</form>

This will do precisely what you asked for:

  • validate that the password and confirm fields are equal without clicking the register button
  • If password and confirm password field will not match it will place an error message at the side of confirm password field and disable registration button

It is advisable not to use a keyup event listener for every keypress because really you only need to evaluate it when the user is done entering information. If someone types quickly on a slow machine, they may perceive lag as each keystroke will kick off the function.

Also, in your form you are using labels wrong. The label element has a "for" attribute which should correspond with the id of the form element. This is so that when visually impaired people use a screen reader to call out the form field, it will know text belongs to which field.

Nate
  • 322
  • 2
  • 4
3
function check() {
    if(document.getElementById('password').value ===
            document.getElementById('confirm_password').value) {
        document.getElementById('message').innerHTML = "match";
    } else {
        document.getElementById('message').innerHTML = "no match";
    }
}
<label>password :
<input name="password" id="password" type="password" />
</label>
<label>confirm password:
<input type="password" name="confirm_password" id="confirm_password" onchange="check()"/> 
<span id='message'></span>
Al.G.
  • 4,327
  • 6
  • 31
  • 56
2

HTML CODE

        <input type="text" onkeypress="checkPass();" name="password" class="form-control" id="password" placeholder="Password" required>

        <input type="text" onkeypress="checkPass();" name="rpassword" class="form-control" id="rpassword" placeholder="Retype Password" required>

JS CODE

function checkPass(){
         var pass  = document.getElementById("password").value;
         var rpass  = document.getElementById("rpassword").value;
        if(pass != rpass){
            document.getElementById("submit").disabled = true;
            $('.missmatch').html("Entered Password is not matching!! Try Again");
        }else{
            $('.missmatch').html("");
            document.getElementById("submit").disabled = false;
        }
}
Chandrahasa Rai
  • 427
  • 1
  • 5
  • 10
0

try using jquery like this

$('input[type=submit]').click(function(e){
if($("#password").val() == "")
{
alert("please enter password");
return false;
}
});

also add this line in head of html

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script>
krishna
  • 4,069
  • 2
  • 29
  • 56
0
$('input[type=submit]').on('click', validate);


function validate() {
  var password1 = $("#password1").val();
  var password2 = $("#password2").val();

    if(password1 == password2) {
       $("#validate-status").text("valid");        
    }
    else {
        $("#validate-status").text("invalid");  
    } 
}

Logic is to check on keyup if the value in both fields match or not.

Community
  • 1
  • 1
Gaurav
  • 1,078
  • 2
  • 8
  • 18
0
   <form id="form" name="form" method="post" action="registration.php" onsubmit="return check()"> 
       ....
   </form>

<script>
  $("#form").submit(function(){
     if($("#password").val()!=$("#confirm_password").val())
     {
         alert("password should be same");
         return false;
     }
 })
</script>

hope it may help you

Kalpit
  • 4,906
  • 4
  • 25
  • 43
0

Try this one ;

CSS

#indicator{
    width:20px;
    height:20px;
    display:block;
    border-radius:10px;
}
.green{
    background-color:green; 
    display:block;
}
.red{
    background-color:red;   
    display:block;
}

HTML

<form id="form" name="form" method="post" action="registration.php"> 
    <label >username : 
    <input name="username" id="username" type="text" /></label> <br>
    <label >password : 
    <input name="password" id="password" type="password" id="password" /></label>      <br>
    <label>confirm password:
    <input type="password" name="confirm_password" id="confirm_password" /><span id="indicator"></span> <br>
    </label>
    <label>
    <input type="submit" name="submit" id="regbtn"  value="registration"  />
    </label>
</form>

JQuery

$('#confirm_password').keyup(function(){
    var pass    =   $('#password').val();
    var cpass   =   $('#confirm_password').val();
    if(pass!=cpass){
        $('#indicator').attr({class:'red'});
        $('#regbtn').attr({disabled:true});
    }
    else{
        $('#indicator').attr({class:'green'});
        $('#regbtn').attr({disabled:false});
    }
});
Sherin Jose
  • 2,508
  • 3
  • 18
  • 39
0

WITHOUT clicking the button you will have to listen to the change event of the input fields

var confirmField = document.getElementById("confirm_password");
var passwordField = document.getElementById("password");

function checkPasswordMatch(){
    var status = document.getElementById("password_status");
    var submit = document.getElementById("submit");

    status.innerHTML = "";
    submit.removeAttribute("disabled");

    if(confirmField.value === "")
        return;

    if(passwordField.value === confirmField.value)
        return;

    status.innerHTML = "Passwords don't match";
    submit.setAttribute("disabled", "disabled");
}

passWordField.addEventListener("change", function(event){
    checkPasswordMatch();
});
confirmField.addEventListener("change", function(event){
    checkPasswordMatch();
});

then add the status element to your html:

<p id="password_status"></p>

and set the submit button id to submit

... id="submit" />

hope this helps you

SparK
  • 5,181
  • 2
  • 23
  • 32
0
$box = $('input[name=showPassword]');

$box.focus(function(){
    if ($(this).is(':checked')) {
        $('input[name=pswd]').attr('type', 'password');    
    } else {
        $('input[name=pswd]').attr('type', 'text');
    }
})
Al.G.
  • 4,327
  • 6
  • 31
  • 56
  • 1
    Could you please elaborate more your answer adding a little more description about the solution you provide? – abarisone Apr 08 '15 at 13:29
0

You can check confirm password by only simple javascript

html

<input type="password" name="password" required>
<input type="password" name="confirmpassword" onkeypress="register()" required>
<div id="checkconfirm"></div>

and in javascript

   function register() {

    var password= document.getElementById('password').value ;
    var confirm= document.getElementById('confirmpassword').value;

    if (confirm!=password){
      var field = document.getElementById("checkconfirm")
      field.innerHTML = "not match";
    }
  }

Also you can use onkeyup instead of onkeypress.

Shojaeddin
  • 1,851
  • 1
  • 18
  • 16
0

The code proposed by #Chandrahasa Rai works almost perfectly good, with one exception!

When triggering function checkPass(), i changed onkeypress to onkeyup so the last key pressed can be processed too. Otherwise when You type a password, for example: "1234", when You type the last key "4", the script triggers checkPass() before processing "4", so it actually checks "123" instead of "1234". You have to give it a chance by letting key go up :) Now everything should be working fine!

#Chandrahasa Rai, HTML code:

<input type="text" onkeypress="checkPass();" name="password" class="form-control" id="password" placeholder="Password" required>

<input type="text" onkeypress="checkPass();" name="rpassword" class="form-control" id="rpassword" placeholder="Retype Password" required>

#my modification:

<input type="text" onkeyup="checkPass();" name="password" class="form-control" id="password" placeholder="Password" required>

<input type="text" onkeyup="checkPass();" name="rpassword" class="form-control" id="rpassword" placeholder="Retype Password" required>
Myxir
  • 11
  • 4
0

I think this example is good to check https://codepen.io/diegoleme/pen/surIK

I can quote code here

<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>

and

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;
Tuananhcwrs
  • 971
  • 7
  • 5