Input Validation and Output Encoding
Treat all external input as untrusted: HTTP parameters, JSON bodies, headers, uploaded files, messages, and untrusted external data.
if (username == null || !username.matches("[A-Za-z0-9_]{3,32}")) {
throw new IllegalArgumentException("Invalid username");
}
Validation is not only about security. It protects downstream components from malformed data and makes API behavior predictable. Output encoding must be appropriate for its context.
Key Takeaways
Validate at trust boundaries.
Use context-specific encoding and safe APIs.
Validation for one sink does not automatically protect another sink.