blog/content/post/quick-tips-javascript-password-verify.md

55 lines
2.4 KiB
Markdown
Raw Normal View History

2017-10-28 18:42:26 +00:00
---
title: "Quick Tips: Javascript Password Verification"
date: 2017-10-28T10:30:49-04:00
draft: false
---
I just had to write client-side password verification for work at [Verodin](https://verodin.com),
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](https://developer.mozilla.org/en-US/docs/Web/Events/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.
```html
...
<p id="message">Choose a password</p>
<form>
<input type="password" id="passwordInput"></input>
<input type="password" id="verifyPassword"></input>
</form>
...
```
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.
```javascript
// 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!