Input validation is crucial for ensuring the reliability, security, and integrity of command-line applications. By implementing robust validation, you can prevent unexpected errors and potential security vulnerabilities.
Validation Strategies
graph TD
A[Input Validation] --> B[Type Checking]
A --> C[Range Validation]
A --> D[Pattern Matching]
A --> E[Custom Validation]
Basic Validation Techniques
1. Built-in Flag Validation
package main
import (
"flag"
"fmt"
"os"
)
func main() {
// Integer range validation
port := flag.Int("port", 8080, "Server port number")
flag.Parse()
// Custom range validation
if *port < 1024 || *port > 65535 {
fmt.Println("Error: Port must be between 1024 and 65535")
os.Exit(1)
}
}
2. Regular Expression Validation
package main
import (
"flag"
"fmt"
"os"
"regexp"
)
func validateEmail(email string) bool {
emailRegex := regexp.MustCompile(`^[a-z0-9._%+\-]+@[a-z0-9.\-]+\.[a-z]{2,4}$`)
return emailRegex.MatchString(email)
}
func main() {
email := flag.String("email", "", "User email address")
flag.Parse()
if *email != "" && !validateEmail(*email) {
fmt.Println("Error: Invalid email format")
os.Exit(1)
}
}
Validation Complexity Levels
Level |
Description |
Complexity |
Basic |
Type checking |
Low |
Intermediate |
Range and format validation |
Medium |
Advanced |
Complex pattern matching |
High |
Custom Validation Functions
package main
import (
"flag"
"fmt"
"os"
)
func validateAge(age int) bool {
return age >= 18 && age <= 120
}
func main() {
age := flag.Int("age", 0, "User's age")
flag.Parse()
if !validateAge(*age) {
fmt.Println("Error: Age must be between 18 and 120")
os.Exit(1)
}
}
Advanced Validation Techniques
- Dependency Validation: Checking relationships between different flags
- Contextual Validation: Validating inputs based on specific application context
- External Validation: Using external libraries or services for complex validations
Best Practices
- Validate early and consistently
- Provide clear error messages
- Use type-safe validation methods
- Implement multiple layers of validation
LabEx recommends treating input validation as a critical aspect of application design, ensuring robust and secure command-line interfaces.