Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create preg_match for password validation allowing (!@#$%)

I would like to create a preg_match function to validate my passowrds, but I'm not sure how to write it to allow the following special characters to be used: !@#$%.

if(!preg_match(?????)$/', $password))

Here are my password rules that I want to work into the regex:

  • May contain letter and numbers
  • Must contain at least 1 number and 1 letter
  • May contain any of these characters: !@#$%
  • Must be 8-12 characters

Thank you for any help you can offer.

like image 355
Mark Rummel Avatar asked Aug 08 '12 22:08

Mark Rummel


People also ask

What is the return value of the preg_match() method?

preg_match() returns 1 if the pattern matches given subject, 0 if it does not, or FALSE if an error occurred.

How to validate password strength in PHP?

Password strength validation is very useful to check whether the password is strong. A strong password makes the user’s account secure and helps to prevent account hacking. Using Regex (Regular Expression), you can easily validate the password strength in PHP.

How to create a password validation form in WordPress?

Create A Password Validation Form 1 Step 1) Add HTML:#N#Example#N#<div class="container">#N#<form action="/action_page.php">#N#<label for="usrname"> Username... 2 Step 2) Add CSS:#N#Style the input fields and the message box:#N#Example#N#/ 3 Style all input fields 4 /#N#input {#N#width:... 5 Step 3) Add JavaScript: More ...

What does the preg_match () function return?

The preg_match () function returns whether a match was found in a string. Required. Contains a regular expression indicating what to search for Required. The string in which the search will be performed


2 Answers

I think this should look like that:

if(!preg_match('/^(?=.*\d)(?=.*[A-Za-z])[0-9A-Za-z!@#$%]{8,12}$/', $password)) {
    echo 'the password does not meet the requirements!';
}

Between start -> ^
And end -> $
of the string there has to be at least one number -> (?=.*\d)
and at least one letter -> (?=.*[A-Za-z])
and it has to be a number, a letter or one of the following: !@#$% -> [0-9A-Za-z!@#$%]
and there have to be 8-12 characters -> {8,12}

As user557846 commented to your question, I would also suggest you to allow more characters, I usually (if i use a maximum) take at least 50 :)

btw, you might want to take a look at this regex tutorial

like image 155
r3bel Avatar answered Sep 18 '22 13:09

r3bel


preg_match('/^(?=.*\d)(?=.*[@#\-_$%^&+=§!\?])(?=.*[a-z])(?=.*[A-Z])[0-9A-Za-z@#\-_$%^&+=§!\?]{8,20}$/',$password)
  • at least one lowercase char
  • at least one uppercase char
  • at least one digit
  • at least one special sign of @#-_$%^&+=§!?
like image 22
Thomas Avatar answered Sep 18 '22 13:09

Thomas