Validate a Semver String — Is It Valid Semantic Versioning?
Check whether a version string is valid semantic versioning. Learn the exact format rules for MAJOR.MINOR.PATCH, pre-release identifiers, and build metadata.
Detailed Explanation
Validating a Semver String
Not every version-like string is valid SemVer. The specification is strict about what counts as a well-formed semantic version.
The Official Format
A valid SemVer string must match this pattern:
MAJOR.MINOR.PATCH[-PRERELEASE][+BUILD]
Where:
- MAJOR, MINOR, PATCH are non-negative integers with no leading zeros
- PRERELEASE (optional) is a series of dot-separated identifiers (alphanumeric and hyphens)
- BUILD (optional) is a series of dot-separated identifiers (alphanumeric and hyphens)
Valid Examples
| String | Valid? | Why |
|---|---|---|
1.2.3 |
✅ | Standard three-part version |
0.0.0 |
✅ | Zeros are valid |
1.2.3-alpha.1 |
✅ | Pre-release identifier |
1.2.3+build.42 |
✅ | Build metadata |
1.2.3-beta.1+sha.abc |
✅ | Both pre-release and build |
Invalid Examples
| String | Valid? | Why |
|---|---|---|
1.2 |
❌ | Missing PATCH component |
01.2.3 |
❌ | Leading zero in MAJOR |
1.2.3.4 |
❌ | Four components not allowed |
v1.2.3 |
❌ | "v" prefix is not part of SemVer |
1.2.3- |
❌ | Empty pre-release identifier |
1.2.3+ |
❌ | Empty build metadata |
1.2.3-beta..1 |
❌ | Empty identifier between dots |
The "v" Prefix Myth
Many ecosystems (Git tags, Go modules) use a v prefix like v1.2.3. This is not part of the SemVer spec — it is a convention layered on top. Strict validation should reject it, but many tools strip it automatically.
Leading Zeros
SemVer explicitly prohibits leading zeros in numeric identifiers: 01.2.3 is invalid. This prevents ambiguity between numeric and string comparison. However, pre-release identifiers like alpha.01 are treated as strings (since they start with zero) and are valid.
Validation Regex
The official SemVer regex is complex, but a simplified version for basic validation:
^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(-[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*)?(\+[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*)?$
Use Case
Validating user input in CI/CD pipelines, package publishing scripts, or version bump tools to ensure only well-formed SemVer strings are accepted before tagging a release.