Quick Tips: Javascript Password Verification

I just had to write client-side password verification for work at Verodin, and it was kinda fun to do. I’ll talk through my approach, and hopefully someone down the road searching for front-end tips desperately finds this post like a light at the end of a tunnel.

The main idea is to bind to event listeners on the form inputs we care about, so that we can receive those events with our password checking functions. As soon as we bind an Object to the event listener, that object has “subscribed” to those events and will receive messages every time that event happens.

I will be binding to the keyup event to provide the user with password verification as they type!

The first step is to setup an html form to work with. I also included a <p> tag to hold a meaningful message for the user.

<p id="message">Choose a password</p>
    <input type="password" id="passwordInput"></input>
    <input type="password" id="verifyPassword"></input>

Once we have this form, we can start coding up some Javascript. We need to write a function that binds to the onkeyup events of both inputs, and then have that function update the page in a meaningful way if the passwords don’t match. First step is to write the function, then the next step is to write the bindings.

// Verify passwords match, update message element
function verifyPassword() {
    var passwordInput = document.getElementById("passwordInput");
    var verifyPassword = document.getElementById("verifyPassword");
    var message = document.getElementById("message");

    message.textContent = passwordInput.value != verifyPassword.value ? "Not matching" : "Matching";

// Bind to onkeyup for passwordInput and verifyPassword
document.getElementById("passwordInput").onkeyup = verifyPassword;
document.getElementById("verifyPassword").onkeyup = verifyPassword;

verifyPassword will now receive messages every time the keyup event fires when passwordInput or verifyPassword are in focus (when users are typing in those boxes). The verification function will update the message box accordingly and alert the user in real time if the passwords they type match!

Thanks for reading, any tips, comments, concerns, or suggestions, leave me a comment below!


comments powered by Disqus