Lesson 2: String Validation
JSON Schema provides several keywords specifically for validating string values. "minLength" and "maxLength" set lower and upper bounds on the number of characters in the string. The "pattern" keyword accepts a regular expression and requires the string to match it — useful for enforcing formats like usernames or phone numbers. "format" checks a semantic format such as "email", "uri", or "date-time", while "enum" restricts the value to an explicit list of allowed strings.
Why This Matters
Strings are the most common primitive in real APIs — usernames, emails, IDs, status codes — and they're also the easiest place for silently-bad data to sneak in, since any string is technically a valid string. Bounding length prevents abuse (a 50,000-character "username"), "pattern" enforces exact shapes like slugs or ZIP codes, and "enum" turns a loosely-typed string field into a closed set of known values — effectively a lightweight, cross-language alternative to an enum type, which is especially valuable in JSON, a format with no native enum.
Common Mistakes
- ✕ Assuming "format": "email" is always strictly enforced.Per the JSON Schema spec, "format" is technically an annotation unless a validator opts into assertion behavior — some validators (like plain Ajv without ajv-formats) ignore it entirely. This playground's validator does check email, uri, date, date-time, ipv4 and uuid as real assertions, but always confirm your production validator does the same.
- ✕ Forgetting anchors (^ and $) in "pattern".JSON Schema's "pattern" matches if the regex is found anywhere in the string, not the whole string, unless you anchor it. "[a-z]+" matches "123abc456" too — use "^[a-z]+$" to require the entire string to match.
- ✕ Using "enum" for a list of values that changes frequently (like a country's list of active promo codes).Reserve "enum" for genuinely fixed, small vocabularies (roles, statuses, currency codes). For dynamic sets, validate against a lookup table in application code instead of hardcoding it into the schema.
- ✕ Counting bytes instead of characters when reasoning about minLength/maxLength.JSON Schema counts Unicode code points, not bytes — a string with emoji or multi-byte characters can hit maxLength sooner than a byte-counting mental model would predict.
Challenge
Change the username to 'ab' (too short) and see the error. Then fix it.