1

I'm working on some password validation on my new project. I have this rules that i want to convert on regex pattern using php preg_match() function:

  • Accept all characters.
  • Except spaces.
  • With minimum of 4 chars.
  • Max 20 chars.

Thanks you in advance!

2

2 Answers 2

4

Try this

(?s)^(\S{4,20})$

Explanation

"(?s)" +     // Match the remainder of the regex with the options: dot matches newline (s)
"^" +        // Assert position at the beginning of the string
"(" +        // Match the regular expression below and capture its match into backreference number 1
   "\\S" +       // Match a single character that is a “non-whitespace character”
      "{4,20}" +      // Between 4 and 20 times, as many times as possible, giving back as needed (greedy)
")" +
"$"          // Assert position at the end of the string (or before the line break at the end of the string, if any)
Sign up to request clarification or add additional context in comments.

Comments

0

This will work. The only requirement in this statement is a minimum of 4 and a maximum of 20 of any of your "allowed" characters.

/^[a-zA-Z0-9\W][\S]{4,20}$/

If you would like to require at least one of each type:

/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*\W)[0-9A-Za-z\W][^\s]{4,20}$/

The second option explained:

//Look ahead for a lower case
(?=.*[a-z])

//Look ahead for an uppercase
(?=.*[A-Z])

//Look ahead for a number
(?=.*\d)

//Look ahead for a non-word character
(?=.*\W)

//Specify allowed characters (not space), minimum of 4, and maximum of 20 chars
[0-9A-Za-z\W][^\s]{4,20}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.