String Type Validation with JSON Schema
Learn how to validate string types in JSON Schema with minLength, maxLength, and pattern constraints. Practical examples for user input validation.
JSON Schema
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"properties": {
"username": {
"type": "string",
"minLength": 3,
"maxLength": 30
},
"bio": {
"type": "string",
"maxLength": 500
}
},
"required": ["username"]
}Test Data
{
"username": "dev_user42",
"bio": "Full-stack developer who loves open-source tools."
}Detailed Explanation
Validating Strings in JSON Schema
The string type is the most frequently used type in JSON Schema. It validates that a value is a sequence of characters and supports several built-in constraints for controlling length and format.
Core String Keywords
{
"type": "string",
"minLength": 3,
"maxLength": 30
}
minLength— the minimum number of Unicode characters. A value of0allows empty strings, while1requires at least one character.maxLength— the maximum number of Unicode characters. Use this to prevent excessively long inputs that could cause storage or display issues.pattern— a regular expression the string must match. The regex dialect is ECMA-262, the same one used in JavaScript.
How the Example Schema Works
The schema above defines an object with two string properties. The username field is required and must be between 3 and 30 characters long. The bio field is optional but, when present, must not exceed 500 characters.
When a validator receives the test data, it checks each property against its constraints:
"dev_user42"has 10 characters, which satisfiesminLength: 3andmaxLength: 30— valid."Full-stack developer who loves open-source tools."is well under 500 characters — valid.usernameis present, satisfying therequiredconstraint.
Common String Validation Patterns
You can combine pattern with length constraints for tighter validation:
{
"type": "string",
"minLength": 3,
"maxLength": 30,
"pattern": "^[a-zA-Z0-9_]+$"
}
This restricts the value to alphanumeric characters and underscores only — perfect for usernames, slugs, or identifiers.
Pitfalls to Avoid
- Unicode length:
minLengthandmaxLengthcount Unicode code points, not bytes. An emoji like😀counts as one character in most implementations, but some older validators differ. - Empty strings vs. missing: A property set to
""is still a string. If you require a non-empty value, setminLength: 1rather than relying onrequiredalone. - Pattern anchoring: JSON Schema does not implicitly anchor regex patterns. Use
^and$explicitly when you want the entire string to match.
Use Case
Use string validation when building API schemas for user registration forms, content management systems, or any endpoint that accepts free-text input. Length constraints prevent abuse, while patterns enforce naming conventions for fields like usernames, slugs, and identifiers.