Validating Inputs
БесплатноБез исполняемых скриптовНе проверенCheck all external inputs for validity - garbage in, nothing out, never garbage out
Об этом скилле
Validating Inputs
Overview
Professional-grade software never outputs garbage regardless of what it receives. "Garbage in, garbage out" is the mark of sloppy, insecure code.
Core principle: Check all data from external sources. Validate all routine parameters from untrusted sources. Decide consciously how to handle invalid data.
Modern standard: "Garbage in, nothing out" OR "Garbage in, error message out" OR "No garbage allowed in"
Violating the letter of this rule is violating the spirit of defensive programming.
When to Use
Always use when writing functions that receive:
- User input (forms, command-line args, uploaded files)
- External API responses
- Database query results
- File contents
- Network data
- Configuration files
- Any data from outside your direct control
Warning signs you need this:
- Function assumes inputs are valid
- No validation beyond empty/null checks
- No assertions documenting assumptions
- Spec mentions constraints but code doesn't check them
- Silent failures or wrong results with bad data
- Security vulnerabilities (injection, overflow, etc.)
- Functions accept any input without question
Don't skip when:
- "Inputs will always be valid" (they won't)
- "Validation happens elsewhere" (defense in depth - check anyway)
- "It's just internal code" (today's internal is tomorrow's API)
- Under time pressure (validation prevents longer debugging)
The Two-Level Defense
Level 1: Assertions (Should NEVER Happen)
Use for: Conditions that indicate bugs in YOUR code
def calculate_velocity(distance: float, time: float) -> float:
# Preconditions: These should NEVER be violated if caller is correct
assert distance >= 0, "distance cannot be negative"
assert time > 0, "time must be positive"
result = distance / time
# Postcondition: Result should be reasonable
assert result >= 0, f"velocity cannot be negative: {result}"
return result
Assertions are:
- Executable documentation
- Compiled out in production (typically)
- For catching programmer errors during development
- Should fire = bug in code that needs fixing
Level 2: Error Handling (MIGHT Happen)
Use for: Conditions you expect might occur in production
def calculate_average_score(scores: list[float]) -> float:
"""Calculate average of test scores (must be 0-100)."""
# Error handling: Validate external data
if scores is None:
raise ValueError("scores cannot be None")
if not scores:
raise ValueError("Cannot calculate average of empty score list")
# Validate each score
for i, score in enumerate(scores):
if not isinstance(score, (int, float)):
raise TypeError(f"Score {i} is not a number: {score}")
if score < 0 or score > 100:
raise ValueError(f"Score {i} out of range [0-100]: {score}")
result = sum(scores) / len(scores)
# Postcondition: Verify result is valid
assert 0 <= result <= 100, f"Calculated average out of range: {result}"
return result
Error handling:
- Stays in production code
- Handles expected anomalies gracefully
- Validates external/untrusted data
- Should trigger = need to handle error, not fix code
Quick Reference
| Situation | Approach | Example |
|---|---|---|
| External data | Validate everything | Check ranges, types, formats, lengths |
| Routine parameters | Check if from untrusted source | Validate or document assumptions |
| Internal invariants | Assert they hold | Assert postconditions, state assumptions |
| Null/None | Check explicitly | if value is None: raise ValueError() |
| Empty collections | Decide if valid or error | Empty list error or return default? |
| Type mismatches | Check with isinstance | if not isinstance(score, (int, float)) |
| Range violations | Check bounds | if score < 0 or score > 100 |
| Invalid formats | Use regex/validators | Email, phone, URLs |
| Security risks | Validate aggressively | SQL injection, buffer overflow, path traversal |
Validation Checklist
Before implementing any function receiving external data:
1. Identify all inputs
- What data comes from outside my control?
- Which parameters could be bad?
- What are the data sources? (user, API, DB, file, network)
2. Document constraints
- What are valid ranges? (0-100, positive only, etc.)
- What are valid types? (int, float, string)
- What are valid formats? (email, phone, date)
- What are valid lengths? (string max, array min/max)
- Are nulls allowed?
- Are empties allowed?
3. Think "what could go wrong?"
- Wrong type passed
- Null/None passed
- Empty collection passed
- Negative where positive expected
- Out of range values
- Invalid format (malformed email, etc.)
- Security attacks (injection, overflow)
4. Implement validation
- Check each constrai
Установить Validating Inputs в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл Validating Inputs?
Check all external inputs for validity - garbage in, nothing out, never garbage out
Как установить скилл Validating Inputs?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл Validating Inputs запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic