Skip to main content
AllDevToolsHub
Back to all patterns

Semantic Version (SemVer) Validation

Validation

Validates semantic version strings like 1.2.3, 1.0.0-alpha.1, and 2.0.0+build.123.

/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/

How it works

This is the official SemVer.org regex. It validates MAJOR.MINOR.PATCH with optional pre-release identifiers (e.g., -alpha.1, -rc.2) and build metadata (e.g., +build.123). Leading zeros in numeric identifiers are rejected per the spec.

Test Cases

Should Match

  • 1.0.0
  • 2.3.4-alpha.1
  • 1.0.0-rc.1+build.123

Should NOT Match

  • 1.0
  • 01.0.0
  • 1.0.0.0

Quick Summary

Validates semantic version strings per the SemVer 2.0.0 specification. Matches MAJOR.MINOR.PATCH with optional pre-release (-alpha.1) and build metadata (+build.123). Rejects leading zeros in numeric identifiers.

Key Takeaways

Key Takeaways

  • Validates MAJOR.MINOR.PATCH, all three components required
  • Optional pre-release: -alpha, -beta.1, -rc.2 etc.
  • Optional build metadata: +build.123, +sha.abc123 etc.
  • Leading zeros in numeric identifiers are invalid per SemVer spec (01.0.0 is rejected)
Use Cases

When to use it

  • Validating version fields in package.json or manifest files
  • Checking version strings in CI/CD pipelines before publishing
  • Parsing version ranges in dependency management tools
Watch out

Common Mistakes

  • Using a simpler \d+\.\d+\.\d+ pattern that allows leading zeros and misses pre-release
  • Confusing build metadata (+) with pre-release (-), build metadata does not affect version precedence
FAQ

Semantic Version (SemVer) Validation, Frequently Asked

Is 1.0 a valid SemVer?

No. SemVer requires all three components: MAJOR.MINOR.PATCH. Use 1.0.0 instead.

How does SemVer precedence work?

1.0.0-alpha < 1.0.0-alpha.1 < 1.0.0-beta < 1.0.0. Build metadata (+) is ignored for precedence.