Files
scripts/lib/common/validation.sh
2026-02-09 21:51:52 -08:00

87 lines
1.8 KiB
Bash
Executable File

#!/usr/bin/env bash
# Input validation functions
# Usage: source "$(dirname "$0")/validation.sh"
# Requires: logging.sh
# Validate project name (alphanumeric, hyphens, underscores)
validate_project_name() {
local name="$1"
if [ -z "$name" ]; then
log_error "Project name is required"
return 1
fi
if [[ ! "$name" =~ ^[a-zA-Z0-9_-]+$ ]]; then
log_error "Invalid project name: $name (must be alphanumeric with hyphens/underscores only)"
return 1
fi
return 0
}
# Validate environment name
validate_environment() {
local env="$1"
local valid_envs=("development" "dev" "staging" "stg" "production" "prod" "test")
if [ -z "$env" ]; then
log_error "Environment is required"
return 1
fi
for valid_env in "${valid_envs[@]}"; do
if [ "$env" = "$valid_env" ]; then
return 0
fi
done
log_error "Invalid environment: $env (must be one of: ${valid_envs[*]})"
return 1
}
# Validate URL format
validate_url() {
local url="$1"
if [ -z "$url" ]; then
log_error "URL is required"
return 1
fi
if [[ ! "$url" =~ ^https?:// ]]; then
log_error "Invalid URL format: $url (must start with http:// or https://)"
return 1
fi
return 0
}
# Validate port number
validate_port() {
local port="$1"
if [ -z "$port" ]; then
log_error "Port is required"
return 1
fi
if ! [[ "$port" =~ ^[0-9]+$ ]] || [ "$port" -lt 1 ] || [ "$port" -gt 65535 ]; then
log_error "Invalid port: $port (must be 1-65535)"
return 1
fi
return 0
}
# Validate non-empty string
validate_non_empty() {
local value="$1"
local name="${2:-Value}"
if [ -z "$value" ]; then
log_error "$name is required and cannot be empty"
return 1
fi
return 0
}