Regular Expression to validate password - PHP

Asked

Viewed 450 times

2

I searched here in the OS and tbm in Google, but I did not find something to act as I would like, I am also not good with regular expressions, I confess that I have some difficulty and I would like to do a password validation in PHP that:

  • Have at least 8 characters (this I check using strlen());
  • Have at least 1 number;
  • At least 1 capital letter;
  • Has at least 1 lower case letter;
  • Has at least 1 special character;

If anyone can give me a light, I’d be grateful.

  • 1

    It can be based on this: https://answall.com/q/337924/112052

  • 3

    If the encoding for UTF8 might be better to use mb_strlen() otherwise an accented character can count as more than 1 byte.

  • 1

    @hkotsubo Thank you so much for the base, will help me mto yes, just give an implemented!

  • @fernandosavio Thank you so much for remembering this detail that tbm went unnoticed! Vcs are too much!

  • so I leave 100% I will post here the answer

  • 1

    Ah, and "special characters" is a "vague" definition, since each one defines a way (which is the exact list of special characters? It depends, each one implements a way) So you must define which will accept and which will not, gives a read here also: https://en.stackoverflow.com/a/342737/112052

  • 2
Show 2 more comments

1 answer

1

It’s been a long time, but here’s a chance to validate only with a pure regex:

/(?!\s)(?=.*?[a-z]{1,})(?=.*?[A-Z]{1,})(?=.*?\d{1,}).*(?=.?[^a-zA-Z0-9]{1,})?.([^\s]){8,}/g

In the last parentheses, inside the square bracket, you can delete all the characters you want, for example, if you want to remove quotes:

([^\s'"`])

Testing:

regexr

Explaining a little:

When you want more than one rule in regex, where you need to go through them all, you use (?=seu_regex) (would be similar to && in programming languages).

As in this case, no matter the order of what was typed, as long as it has all the characters, so for each desired rule, you use: .*?, something like "regardless of how many or what comes before, validate my rule". Soon:

(?=.*?seu_regex)

When you need to quantify your rules, just use {n} for an exact amount, or {n,} for "from". So, if you wanted to force at least four lower-case letters, {4,}. Following the case of your question:

(?=.*?seu_regex{1,})

Browser other questions tagged

You are not signed in. Login or sign up in order to post.