I'm trying to write a password requirement checker.. however regex is causing some issues, any suggestions?
regex="^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@$!%*?&])([a-zA-Z0-9@$!%*?&]{7,16})$"
CodePudding user response:
This is the kind of thing that benefits from multiple tests:
password=$1
length=${#password}
# separate regular expressions
lower='[abcdefghijklmnopqrstuvwxyz]'
upper="${lower^^}"
digit='[0123456789]'
punct='[@$!%*?&]'
if [[ $password =~ $upper ]] &&
[[ $password =~ $lower ]] &&
[[ $password =~ $digit ]] &&
[[ $password =~ $punct ]] &&
(( 7 <= length && length <= 16 ))
then
echo OK
else
echo not OK
fi
It would be helpful for users to tell then which criteria are failing.
CodePudding user response:
I wouldn't use a singular regex statement, as it's pretty complicated . Why not use Linux's already built in checks in a simple if
? Some of which is regex-ish .. But it can be broken down easier, and managed.
#!/bin/bash
read password
if [[ ${#password} -ge 7 && ${#password} -le 16 && "$password" == *[A-Z]* && "$password" == *[a-z]* && "$password" == *[0-9]* ]]; then
echo "Password match the criteria"
else
echo "It doesn't match the criteria"
-ge
- greater than or equal to in length
-le
- less than or equal to in length
== *[A-Z]*
contains caps
== *[a-z]*
contains lowers
== *[0-9]*
contains numbers
=~ ['!@#$%^&*()_ ']
contains special character #must be in the list
You can continue with these "mini" checks as many as you wish to tailor the statement to your needs, without affecting a huge regex statement.
CodePudding user response:
You can use something like this:
if [[ ${#password} -ge 7 && "$password" == *[a-zA-Z0-9]* && "$password" =~ ['!@#$%^&*()_ '] && -le 16 ]]; then
echo "Password is valid"
else
echo "Something with password is wrong!"
fi
So, you check the string for parameters such as:
- More or equal 7 symbols
- Less or equal 16 symbols
- Minimum 1 Upper-Case symbol
- Minimum 1 Lower-Case symbol
- Minimum 1 Number
- Minimum 1 Special char