What is wrong with this PHP regex to do password validation?

后端 未结 2 772
感情败类
感情败类 2020-12-20 06:49
ereg(\"/^(?=.*[a-z])(?=.*[0-9])(?=.*[^a-zA-Z0-9])(?=.*[A-Z]).{7,19}$/\",\"ABCabc123!!\");

This is supposed to be a password validator, requiring al

2条回答
  •  死守一世寂寞
    2020-12-20 07:49

    Don't try to do it all in one regex. Make multiple regex checks.

    I know you're writing PHP, but I know Perl better, so follow along and get the idea.

    my $password_is_valid =
        length($pw) >= 8 &&  # Length >= 8
        ($pw =~ /[a-z]/) &&  # Has lowercase
        ($pw =~ /[A-Z]/) &&  # Has uppercase
        ($pw =~ /\W/);       # Has special character
    

    Sure, that takes up five lines instead of one, but in a year when you go back and have to add a new rule, or figure out what the code does, you'll be glad you wrote it that way. Maybe you require a digit later on. Easy!

    my $password_is_valid =
        length($pw) >= 8 &&  # Length >= 8
        ($pw =~ /\d/)    &&  # Has digit
        ($pw =~ /[a-z]/) &&  # Has lowercase
        ($pw =~ /[A-Z]/) &&  # Has uppercase
        ($pw =~ /\W/);       # Has special character
    

    Just because you can do it in one regex doesn't mean you should.

提交回复
热议问题