API Input Validation Regex Patterns (Without Over-Blocking Users)
Regex should enforce shape, not business truth. For API input validation, this means combining strict boundaries with semantic checks in code.
Common field patterns
- Slug:
/^[a-z0-9]+(?:-[a-z0-9]+)*$/ - SemVer:
/^v?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/ - ISO date:
/^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$/
Always pair regex with clear API error messages. Validation that says why it failed is easier for integrators to fix quickly.