acbarker15
acbarker15

Reputation: 15

How to require some characters and restrict others with Regex in HTML input pattern

As a user is typing their new password, I want them to be able to see if their password meets the requirements or not. I have a Regex pattern set up inside the input tag, and if the requirements aren't met, the input box is outlined in red and the form can't be submitted. This looks like:

<input type="password" pattern="((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.[!@@#$%&?]).{8,32})" placeholder="Password" required />

I adapted that pattern from here. I have it so that the user's password must contain 8-32 characters, one uppercase letter, one lowercase letter, one special character (!@#$%&?), and one number, and that works fine. However, I also want to exclude some special characters from the input, for example, the semicolon (;). I have tried adding (?!.[;]) like so:

((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.[!@@#$%&?])(?!.[;]).{8,32})

This breaks the entire pattern, though. Could someone explain what I am doing wrong and how I can fix it? Or would it be better to do this manually by using a Javascript listener to check if the password meets the requirements each time the user does a keypress?

Upvotes: 0

Views: 1105

Answers (1)

SeaBean
SeaBean

Reputation: 23217

Try with:

((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@@#$%&?])(?!.*[;]).{8,32})

Fine-tunings from your regex:

  1. Added back an asterisk * to the positive lookahead for symbols list [!@@#$%&?]
  2. Added back an asterisk * to the negative lookahead for symbol [;]

You need an asterisk * after the dot . in order to allow matching of multiple characters (by *) for any character (by .). Otherwise, your regex allows only ONE single character before the symbols to include and exclude.

Upvotes: 1

Related Questions