format

package
v0.52.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 4, 2026 License: Apache-2.0 Imports: 20 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

schema/format

String-format validators for the schema package. Each exported function (Email, Language, Color, ObjectID, UUID, IPv4, IPv6, Hostname, URI, URL, Date, DateTime, Time, ISO8601, HTML, NoHTML, Text, Markdown, CSS, CSSDeclarations, In, NotIn, MatchRegex, HasLowercase, HasUppercase, HasNumbers, Token, Username, WebFinger, UnsafeAny) is a Generator — it takes a configuration arg and returns a StringFormat closure that validates (and may rewrite) a string. See the parent schema README.

What matters here

  • A format is registered via schema.UseFormat, which is only safe during init/startup. The registry freezes the first time validation reads from it; registering a format afterward is rejected (reported, then ignored). Register all custom formats before any schema validation runs.

  • Empty string is always allowed. Every validator returns early on "" without error — "required" is enforced by the schema element (String.Required), not by the format. A format only constrains the shape of a non-empty value.

  • A StringFormat returns (value, error) and may REWRITE the value. Validators are part of a coercion pipeline (see validate_String and applyStringFormats in the parent package's validate_string.go), so returning a changed string is normal, not a bug — the caller tracks the change.

  • Many Generators ignore their arg (e.g. Email, IPv4); the parameter exists to satisfy the uniform Generator signature. In/NotIn/MatchRegex and HasLowercase/HasUppercase/HasNumbers are the ones that actually consume arg (the allowed set, the pattern, or the minimum count).

  • The validators here are the trust boundary for untrusted strings. NoHTML/HTML gate markup (and lean on ../../html + bluemonday); URI/Hostname/IP* constrain network identifiers. Tighten here, not at call sites.

  • Markup formats are guarded; unsafe-any is the only escape hatch. html sanitizes and markdown validates. A field whose safety is owned by a different trust boundary has to opt out with unsafe-any, which is deliberately generic and blunt — say why in a comment wherever you reach for it.

  • A second sanitize is not automatically safer. This package's HTML policy is deliberately strict (no iframes, no styling, rel="nofollow" added). Re-filtering markup that an application already sanitized under its own wider policy silently deletes content — embeds especially. When an application's renderer has already sanitized a value, do not run it through html again; stacking two policies is safe by accident, not by design.

  • css sanitizes a whole stylesheet; bluemonday only ever sees the declarations. Bluemonday is an HTML sanitizer, so it cannot be pointed at a stylesheet — CSS.go parses the rule structure itself (comments, selectors, brace-balanced blocks, nested @media/@supports) and round-trips each declaration block through a policy as an element's style attribute. Both halves are allowlists: a property survives only if it is named in cssAllowedProperties, a value only if it passes isSafeCSSValue, and a selector only if every character is in the prelude set. Everything else — unknown at-rules, unbalanced blocks, trailing garbage — is dropped, not repaired.

  • css and css-declarations read the same input differently, and each empties what the other keeps. css parses rule structure, so a bare declaration list has no selector or block in it and sanitizes to ""; css-declarations filters declarations, so a stylesheet's selector and braces are not properties and it empties too. Both return a nil error either way, so pointing a schema at the wrong one is silent — the stored value simply becomes empty. Use css-declarations for the contents of a style attribute and css for a <style> element. They share the allowlists below, so the two agree about what is safe; they disagree only about what shape the input is.

  • The css allowlists encode threat decisions, so read the comments before widening them. @import and @font-face are absent because they fetch a remote resource (leaking the viewer's IP and, for @import, pulling in unsanitized rules); url and expression are rejected by name because the character allowlist admits ( and ) and so cannot block them; position is allowed only as static/relative, because a stylesheet injected into a page it does not own could otherwise lift an element out of the flow to cover unrelated page chrome. Quoted strings are rejected outright, which is what costs content: and quoted font names.

  • css reformats what it keeps, and that reformatting is important. Declarations are normalized to one line before the round trip — every run of whitespace becomes a single space and empty declarations are dropped — so an author's indentation never survives. It also must not: bluemonday trims only the space character before appending its own ;, so a block ending red;\n becomes red;\n;, and the empty declaration that creates fails the CSS parse and empties the whole attribute. Without normalizing, every rule written with its closing brace on its own line sanitized away to nothing, silently and with a nil error. CSS_fuzz_test.go pins the general form of that: re-indenting a stylesheet may never change how many rules survive it.

  • A sanitized stylesheet is still global. css guarantees the rules it emits cannot escape a <style> element, load a resource, or run script — it does not scope them. Rules still apply to the whole document, so an application embedding one in a shared page owns the scoping.

  • Markdown cannot be made safe by rewriting its source. Sanitizing the source is a category error: it corrupts a < b in prose and fenced code blocks that quote markup, and an unregistered format name falls back to NoHTML, which strips tags and collapses the whitespace Markdown depends on. So markdown validates rather than rewrites. It renders the source twice, once honoring raw HTML and once not, and rejects the value when the two disagree — which happens exactly when the source carries raw HTML or a dangerous URL. That test needs no policy and no allow-list, so it can never argue with whatever sanitizer the application applies later: it accepts pure Markdown (links keep no added rel, fenced code keeps its language class) and rejects all embedded HTML, benign tags included. Cost is two renders, linear in length — pair it with a MaxLength, which the schema checks before any format function runs.

Documentation

Overview

Package format provides the named string formats used by the schema package.

Each function here is a Generator: it takes the argument written in the schema (the part after the format name) and returns a StringFormat closure that validates one value. That closure returns the value it accepts, so a format may normalize as well as validate — trimming, case-folding, or rewriting into a canonical form on the way through.

The set covers the usual identifier and network formats (email, hostname, IPv4, IPv6, URI, URL, ObjectID, token, username, WebFinger), dates and times, constraints on the text itself (In, NotIn, MatchRegex, HasUppercase, HasLowercase, HasNumbers), and the content formats that decide how much markup survives (Text, NoHTML, HTML, Markdown, CSS, UnsafeAny).

Those content formats are a trust boundary: the format named on a string element is what decides whether a value is escaped, sanitized, or passed through untouched. Choose UnsafeAny only for values that are already trusted.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Generator added in v0.10.0

type Generator func(string) StringFormat

Generator is a function that takes an optional parameter and generates a StringFormat function

type StringFormat

type StringFormat func(string) (string, error)

StringFormat tries to force a value to fit the desired format. If it cannot safely convert the value into the specified format, then it returns empty string and an error message.

func CSS added in v0.38.0

func CSS(arg string) StringFormat

CSS sanitizes a CSS stylesheet, keeping only the rules that are safe to embed in a page the stylesheet's author does not otherwise control. Selectors are checked against a character allowlist, declarations are filtered by bluemonday against a property allowlist and a value allowlist, and everything unrecognized -- comments, unknown at-rules, unbalanced blocks, trailing garbage -- is discarded rather than repaired.

Like HTML, this format sanitizes rather than rejects: it returns the cleaned stylesheet with a nil error, so a value that is partly unsafe is stored stripped instead of failing the whole write.

The result is reformatted, not echoed: whitespace inside a rule collapses and each block is emitted on one line. An author's indentation does not survive, but neither does it decide what does.

The result is a stylesheet, not a fragment, and it is still global in scope -- nothing here confines its selectors to one subtree. A caller embedding it in a shared page is responsible for scoping the rules it emits.

func CSSDeclarations added in v0.39.0

func CSSDeclarations(arg string) StringFormat

CSSDeclarations sanitizes ONE list of CSS declarations -- the contents of an element's `style` attribute -- rather than a whole stylesheet. It applies the same property and value allowlists as CSS, so a declaration list can be accepted from the same authors and trusted to the same degree.

Use it wherever the stored value is written into a `style` attribute. Passing such a value to CSS instead discards it entirely: that format parses rules, finds no selector or block, and returns "".

Like CSS, this sanitizes rather than rejects, returning the cleaned value with a nil error. A declaration list containing a quote is dropped whole, because the quote is what the sanitizer's own round trip is delimited by.

func Color added in v0.21.0

func Color(arg string) StringFormat

Color returns a StringFormat that validates a six-digit hexadecimal color (e.g. "#336699").

func Date

func Date(arg string) StringFormat

Date returns a StringFormat that validates a value as an RFC-3339 full-date (e.g. "2026-03-04").

func DateTime

func DateTime(arg string) StringFormat

DateTime returns a StringFormat that validates a value as an RFC-3339 date-time (e.g. "2026-03-04T13:02:00Z").

func Email

func Email(arg string) StringFormat

Email validates an email address using Go's built-in system email parser.

func HTML

func HTML(arg string) StringFormat

HTML allows basic HTML tags, but strips iframes, object, embed, style, script tags.

func HasLowercase

func HasLowercase(arg string) StringFormat

HasLowercase returns a StringFormat requiring at least arg lowercase letters (default 1).

func HasNumbers

func HasNumbers(arg string) StringFormat

HasNumbers returns a StringFormat requiring at least arg numeric digits (default 1).

func HasUppercase

func HasUppercase(arg string) StringFormat

HasUppercase returns a StringFormat requiring at least arg uppercase letters (default 1).

func Hostname

func Hostname(arg string) StringFormat

Hostname returns a StringFormat that validates a value as an RFC-1123 hostname.

func IPv4

func IPv4(arg string) StringFormat

IPv4 returns a StringFormat that validates a value as an IPv4 address.

func IPv6

func IPv6(arg string) StringFormat

IPv6 returns a StringFormat that validates a value as an IPv6 address.

func ISO8601 added in v0.25.25

func ISO8601(arg string) StringFormat

ISO8601 returns a StringFormat that validates an ISO-8601 date and time, e.g. "2026-03-04T13:02".

func In

func In(arg string) StringFormat

In returns a StringFormat that requires the value to be one of the comma-separated options in arg.

func Language added in v0.46.0

func Language(_ string) StringFormat

Language accepts an empty value or any usable BCP 47 language tag, rewriting it to its canonical form so that one language is always stored with one spelling ("EN-us" is "en-US").

func Markdown added in v0.35.0

func Markdown(arg string) StringFormat

Markdown accepts Markdown source that renders safely under any renderer, and rejects source carrying raw HTML or a dangerous URL.

func MatchRegex

func MatchRegex(arg string) StringFormat

MatchRegex returns a StringFormat that requires the value to match the regular expression arg.

func NoHTML

func NoHTML(arg string) StringFormat

NoHTML strips all HTML tags from a string and collapses whitespace into a single space character.

func NotIn

func NotIn(arg string) StringFormat

NotIn returns a StringFormat that rejects the value if it is one of the comma-separated options in arg.

func ObjectID

func ObjectID(arg string) StringFormat

ObjectID validates a mongodb-style identifier (24 hexadecimal characters)

func Text added in v0.29.0

func Text(arg string) StringFormat

Text strips all HTML tags from a string without collapsing whitespace.

func Time

func Time(arg string) StringFormat

Time returns a StringFormat that validates an RFC-3339 full-time ("13:02:00" or "13:02:00Z"), or a time to the minute ("13:02").

func Token

func Token(_ string) StringFormat

Token validates a simple token string suitable for use as URL identifiers

func URI

func URI(arg string) StringFormat

URI returns a StringFormat that validates a value as an absolute URI.

func URL added in v0.31.0

func URL(arg string) StringFormat

URL returns a StringFormat that validates a value as an absolute URL — one that parses with both a scheme and a host. This is stricter than URI, which also accepts opaque values like "mailto:" addresses and "urn:" references that have no host.

func UUID added in v0.44.0

func UUID(_ string) StringFormat

UUID validates a UUID, and stores it in its canonical lowercase form. A URL whose last path segment is a UUID (such as a MusicBrainz page) is accepted, and only the UUID is kept.

func UnsafeAny added in v0.7.0

func UnsafeAny(arg string) StringFormat

UnsafeAny leaves the string format untouched.

func Username added in v0.24.8

func Username(_ string) StringFormat

Username validates a simple token string suitable for use as URL identifiers

func WebFinger added in v0.25.9

func WebFinger(arg string) StringFormat

WebFinger validates a Fediverse handle of the form "@user@host" and returns it unchanged.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL