Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Password validation php regex

Tags:

regex

php

I'm new to regex.
I need to validate passwords using php with following password policy using Regex:

Passwords:

  1. Must have minimum 8 characters
  2. Must have 2 numbers
  3. Symbols allowed are : ! @ # $ % *

I have tried the following: /^(?=.*\d)(?=.*[A-Za-z])[0-9A-Za-z!@#$%]$/

like image 670
sash Avatar asked Aug 11 '13 19:08

sash


People also ask

How can I get password and confirm password in PHP?

Just get both the password and confirm password fields in the form submit PHP and test for equality: if ($_POST["password"] === $_POST["confirm_password"]) { // success! } else { // failed :( } where password and confirm_password are the IDs of the HTML text inputs for the passwords.

What is the regex for special characters?

Special Regex Characters: These characters have special meaning in regex (to be discussed below): . , + , * , ? , ^ , $ , ( , ) , [ , ] , { , } , | , \ . Escape Sequences (\char): To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ).


1 Answers

The following matches exactly your requirements: ^(?=.*\d.*\d)[0-9A-Za-z!@#$%*]{8,}$

Online demo <<< You don't need the modifiers, they are just there for testing purposes.

Explanation

  • ^ : match begin of string
  • (?=.*\d.*\d) : positive lookahead, check if there are 2 digits
  • [0-9A-Za-z!@#$%*]{8,} : match digits, letters and !@#$%* 8 or more times
  • $ : match end of string
like image 52
HamZa Avatar answered Sep 27 '22 17:09

HamZa