Last active 1736856724

UsernameValidation.sh Raw
1#!/bin/bash
2
3#Validation Function:
4#- Checks if the username is not empty and has at least 5 characters.
5#- Checks if the username contains only letters and numbers with no spaces.
6#- Checks if the username already exists on the system.
7
8#Input and Validation:
9#- Prompts the user to enter a username.
10#- Calls the validation function to check the entered username.
11#- Displays appropriate messages based on the validation result.
12
13# Function to validate the username
14function validate_username() {
15 local username="$1"
16
17 # Check if username is not empty and has at least 5 characters
18 if [[ -z "$username" ]] || [[ ${#username} -lt 5 ]]; then
19 echo "Username must be at least 5 characters long and cannot be empty."
20 return 1
21 fi
22
23 # Check if username contains only lowercase letters and numbers
24 if ! [[ "$username" =~ ^[a-z0-9]+$ ]]; then
25 echo "Username can only contain lowercase letters and numbers, and no spaces."
26 return 1
27 fi
28
29 # Check if the username already exists on the system
30 if id "$username" &>/dev/null; then
31 echo "Username already exists on the system."
32 return 1
33 fi
34
35 return 0
36}
37
38# Get username input from the user
39read -p "Enter username: " username
40
41# Validate the username
42if validate_username "$username"; then
43 echo "Username is valid."
44else
45 echo "Username is invalid. Please try again."
46fi
47