Skip to main content
AllDevToolsHub
Back to all patterns

Git Commit Hash Validation

Validation

Validates Git commit hashes in short (7-char) or full (40-char) SHA-1 format.

/^[0-9a-f]{7,40}$/i

How it works

Git commit hashes are SHA-1 digests represented as 40 hexadecimal characters. Git also accepts abbreviated hashes of at least 7 characters (the minimum to be unambiguous in most repositories). This pattern accepts 7–40 hex characters.

Test Cases

Should Match

  • a1b2c3d
  • a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0

Should NOT Match

  • xyz123
  • a1b2c3
  • a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1

Quick Summary

Validates Git commit hashes in short (7–12 chars) or full (40 chars) SHA-1 format. Case-insensitive. Does not validate that the hash exists in any repository, use git cat-file for that.

Key Takeaways

Key Takeaways

  • Full SHA-1 hash: exactly 40 hex characters
  • Short hash: minimum 7 characters (Git's default abbreviation length)
  • Case-insensitive, Git accepts both uppercase and lowercase hex
  • Does not validate existence, a syntactically valid hash may not exist in your repo
Use Cases

When to use it

  • Validating commit hash inputs in CI/CD pipeline triggers
  • Checking git ref parameters in deployment scripts
  • Parsing git log output for commit references
Watch out

Common Mistakes

  • Accepting fewer than 7 characters, short hashes below 7 chars are ambiguous in large repos
  • Not handling both short and full hashes in the same input field
FAQ

Git Commit Hash Validation, Frequently Asked

Is SHA-1 still safe for Git?

Git uses SHA-1 for content addressing, not security. SHA-1 collision attacks exist but are impractical for Git's use case. Git is transitioning to SHA-256 (git hash-object --format sha256).

How do I get the full hash from a short hash?

Run: git rev-parse <short-hash> to expand it to the full 40-character hash.