phpregexlaravelvalidationlaravel-request

How to combine these regex expressions together


I'm working with Laravel and I have used this custom regular expression for validating user password request:

'user_password'=> ['required','min:6','regex:/[a-z]/','regex:/[A-Z]/','regex:/[0-9]/','regex:/[@$!%*#?&]/']

Now I needed to combine these separated regexs all together but don't know how to do it, so if you know, please let me know.. thx!


Solution

  • One general way to do this via a single regex would be to use positive lookaheads to assert each requirement:

    /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[@$!%*#?&]).{6,}$/
    

    The above pattern says to match:

    ^                 from the start of the user password
    (?=.*[a-z])       at least one lowercase letter
    (?=.*[A-Z])       at least one uppercase letter
    (?=.*[0-9])       at least one digit
    (?=.*[@$!%*#?&])  at least one special character
    .{6,}             then match any 6 or more characters
    $                 end of the password