So when I couldn’t find any sort of safe password regex for a HTML5 input for my upcoming forum, I came up with this one, which is what I’ll be using for all my future projects.
It’s quite safe and can easily be used in any sort of form.
The rules for the password will be the following:
- Must have at least 1 uppercase letter
- Must have at least 1 lowercase letter
- Must have at least 1 number or special character
- Must be between 8 and 100 characters long
HTML 5 code:
<input pattern="^(?=.*[\d\W])(?=.*[a-z])(?=.*[A-Z]).{8,100}$" required type="password" class="validate" />
The required
attribute is required to validate the pattern. Be sure to tell your users the rules for the password input.
Now to make it look red or green depending on the regex we can use the CSS selectors :invalid
and :valid
input.validate:focus:invalid { outline: 0; border: 1px solid #ee6d69; } input.validate:valid[type="text"], input.validate:valid[type="password"], input.validate:valid[type="email"] { outline: 0; border: 1px solid #47cc55; }
The :focus
selector makes it so instead of always showing the textbox as invalid, you’ll first have to focus it. When the input is valid, it’ll keep its green border. We’ll also use outline: 0
to disable the default browser input border focus.
Now you can simply check the password using almost the same regex within PHP:
if(!preg_match('#(?=.*[\d\W])(?=.*[a-z])(?=.*[A-Z]).{8,100}#', $password)){ echo 'Invalid Password'; }
Here’s a JSFiddle for the form: https://jsfiddle.net/z8dvhe06/
Hope this is useful for some people. Good luck!