A signup form receives a username that must follow a defined format.
What You Need to Understand
Sanitization transforms input, validation checks whether input meets requirements, and output escaping protects a specific destination such as HTML. These are different operations and should not be substituted for one another.
When to Use It
A signup form receives a username that must follow a defined format.
Step-by-Step Python Example
raw_username = " maya_27 "
username = raw_username.strip()
is_valid = (3 <= len(username) <= 20 and
all(character.isalnum() or character == "_" for character in username))
print(username)
print(is_valid)
How the Example Works
Trimming whitespace produces a candidate username. Explicit rules decide whether it is accepted; trimming alone did not make it valid.
Example Output
maya_27
True
<script>alert("hello")</script>
A Second Example
Compare this smaller variation with the main example, then experiment with your own values.
import html
user_message = '<script>alert("hello")</script>'
print(html.escape(user_message))
Important Behavior and Edge Cases
Removing disallowed characters silently can turn different inputs into the same identifier. When displaying untrusted text in HTML, use context-appropriate escaping; validation does not replace it.
Try It Yourself
Test "<admin>", an empty value, and a username with a hyphen against the same policy.
Common Beginner Mistakes
- Removing disallowed characters silently can turn different inputs into the same identifier. When displaying untrusted text in HTML, use context-appropriate escaping; validation does not replace it.
- Applying a string method before defining whether text is intended for display, comparison, parsing, or input validation.
Key Takeaways
- Sanitization transforms input, validation checks whether input meets requirements, and output escaping protects a specific destination such as HTML.
- Trimming whitespace produces a candidate username.
- Removing disallowed characters silently can turn different inputs into the same identifier.