| name | argument-validator-generator |
| description | Generate argument validation logic with type coercion, constraints, custom validators, and helpful error messages for CLI applications. |
| allowed-tools | Read, Write, Edit, Bash, Glob, Grep |
| graph | {"domains":["domain:software-engineering"],"specializations":["specialization:cli-mcp-development"],"skillAreas":["skill-area:cli-design","skill-area:cli-tooling"],"roles":["role:backend-engineer","role:platform-engineer"],"workflows":["workflow:feature-development"],"topics":["topic:developer-experience"]} |
Argument Validator Generator
Generate comprehensive argument validation logic for CLI applications with type coercion and constraint checking.
Capabilities
- Generate type coercion functions for arguments
- Create custom validators with constraint checking
- Set up validation error messages
- Implement value normalization
- Configure mutually exclusive validation
- Generate validation schemas
Usage
Invoke this skill when you need to:
- Add type validation to CLI arguments
- Create custom argument validators
- Implement complex constraint checking
- Generate helpful validation error messages
Inputs
| Parameter | Type | Required | Description |
|---|
| language | string | Yes | Target language (typescript, python, go, rust) |
| validators | array | Yes | List of validators to generate |
| outputPath | string | No | Output path for generated files |
Validator Structure
{
"validators": [
{
"name": "port",
"type": "number",
"constraints": {
"min": 1,
"max": 65535
},
"errorMessage": "Port must be between 1 and 65535"
},
{
"name": "email",
"type": "string",
"pattern": "^[\\w.-]+@[\\w.-]+\\.\\w+$",
"errorMessage": "Invalid email format"
},
{
"name": "environment",
"type": "enum",
Generated Code Patterns
TypeScript Validators
import { z } from 'zod';
export const portSchema = z
.number()
.int()
.min(1, 'Port must be at least 1')
.max(65535, 'Port must be at most 65535');
export function validatePort(value: unknown): number {
const parsed = typeof value === 'string' ? parseInt(value, 10) : value;
return portSchema.parse(parsed);
}
export const emailSchema = z
.string()
.email('Invalid email format')
.toLowerCase();
export function validateEmail(value: unknown): string {
return emailSchema.parse(value);
}
const envAliases: Record<string, string> = {
dev: ,
: ,
};
environmentSchema = z
.()
.( envAliases[val] || val)
.(z.([, , ]));
(): {
environmentSchema.(value);
}
Python Validators
from typing import Any, List, Optional, Union
import re
class ValidationError(Exception):
"""Raised when validation fails."""
pass
def validate_port(value: Any) -> int:
"""Validate port number."""
try:
port = int(value)
except (TypeError, ValueError):
raise ValidationError(f"Invalid port number: {value}")
if not 1 <= port <= 65535:
raise ValidationError("Port must be between 1 and 65535")
return port
def validate_email(value: Any) -> str:
"""Validate email address."""
if not isinstance(value, str):
raise ValidationError(f"Email must be a string, got {type(value).__name__}")
pattern = r'^[\w.-]+@[\w.-]+\.\w+$'
if not re.match(pattern, value):
raise ValidationError()
value.lower()
ENV_ALIASES = {: , : }
VALID_ENVIRONMENTS = [, , ]
() -> :
(value, ):
ValidationError()
normalized = ENV_ALIASES.get(value, value)
normalized VALID_ENVIRONMENTS:
ValidationError(
)
normalized
Go Validators
package validators
import (
"fmt"
"regexp"
"strconv"
"strings"
)
type ValidationError struct {
Field string
Message string
}
func (e *ValidationError) Error() string {
return fmt.Sprintf("%s: %s", e.Field, e.Message)
}
func ValidatePort(value string) (int, error) {
port, err := strconv.Atoi(value)
if err != nil {
return 0, &ValidationError{
Field: "port",
Message: fmt.Sprintf("invalid port number: %s", value),
}
}
if port < 1 || port > 65535 {
return 0, &ValidationError{
Field: "port",
Message: "port must be between 1 and 65535",
}
}
return port, nil
}
func ValidateEmail(value string) (string, error) {
pattern := `^[\w.-]+@[\w.-]+\.\w+$`
matched, _ := regexp.MatchString(pattern, value)
!matched {
, &ValidationError{
Field: ,
Message: ,
}
}
strings.ToLower(value),
}
envAliases = []{
: ,
: ,
}
validEnvironments = []{, , }
(, ) {
alias, ok := envAliases[value]; ok {
value = alias
}
_, env := validEnvironments {
env == value {
value,
}
}
, &ValidationError{
Field: ,
Message: fmt.Sprintf(, value),
}
}
Validation Patterns
Composite Validators
export const apiUrlSchema = z
.string()
.url()
.refine(
(url) => url.startsWith('https://'),
'API URL must use HTTPS'
);
export const existingFileSchema = z
.string()
.refine(
(path) => fs.existsSync(path),
(path) => ({ message: `File not found: ${path}` })
);
Dependent Validation
export const dateRangeSchema = z.object({
startDate: z.coerce.date(),
endDate: z.coerce.date(),
}).refine(
(data) => data.endDate > data.startDate,
'End date must be after start date'
);
Workflow
- Analyze requirements - Review validation needs
- Generate base validators - Type coercion and basic checks
- Add constraints - Min/max, patterns, enums
- Create error messages - Helpful, actionable messages
- Add aliases/transforms - Normalize input values
- Generate tests - Validation test cases
Best Practices Applied
- Type coercion before validation
- Descriptive error messages
- Input normalization (lowercase, trim)
- Alias support for common values
- Composable validation schemas
- Consistent error types
Target Processes
- argument-parser-setup
- error-handling-user-feedback
- cli-command-structure-design