[Code Example] Check if string is valid username using bash script


In this article we will provide you bash script code to check if string is a valid username. A username can have lowercase alphanumeric, underscore and dash. It could be 3 to 15 characters long.

Code Example –

is_valid_username() {
    [[ "$1" =~ ^[a-z0-9_-]{3,16}$ ]] && echo $1

# This username is bad
username="[email protected]"

# regex validation will fail
is_valid_username "$username" || echo "Bad username - $username"

is_valid_username "$good_username" || echo "Bad username - $good_username"

# Output:
# Bad username - [email protected]
# tony_ironman0

Live Demo

Demo might not work in private window (incognito)

Sign Up for Our Newsletters

Get only the best articles delivered to your mail

You May Also Like