We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

When to Sanitize

Of course, there are times when sanitization makes sense. For example, you might want to remove trailing and leading whitespace from the username input silently, as most users expect that behavior. But you still should have a validation step that rejects invalid ones.

For example, you might use it when:

  • Sanitizing rich text fields (comments, posts) that allow a limited set of formatting options like bold and italics
  • Removing unsupported control characters from text that will be stored or processed
  • Escaping characters that won't render correctly in your chosen output format (e.g., replacing \n with <br> in HTML)

Sanitize to a Policy

Here's a "create comment" handler that validates input, sanitizes it to a small allowlist of HTML tags, and saves it:

content := request.FormValue("content")
if utf8.RuneCountInString(content) > 280 {
  http.Error(responseWriter, "Invalid content", http.StatusBadRequest)
  return
}

sanitizedContent := richTextPolicy.Sanitize(content)
if strings.TrimSpace(sanitizedContent) == "" {
  http.Error(responseWriter, "Empty content", http.StatusBadRequest)
  return
}

saveComment(sanitizedContent) // Error handling omitted for brevity.
responseWriter.WriteHeader(http.StatusCreated)

Notice that validation happens first, and sanitization is tightly scoped.

Assignment

Bearly Secure validates review bodies before removing surrounding whitespace. Trim reviews before checking whether they are empty or longer than 1,000 characters.

With Bearly Secure still running, run and submit the CLI tests from the project root.