JavaScript check if a string is valid short git commit ID using check-more-types library

In this JavaScript tutorial we learn how to check whether a given string is a valid 7 characters short SHA git commit ID using the check-more-types library.

Create the sample project

Firstly we create an empty project with the following command.

mkdir sample-project
cd sample-project
npm init -y

And install the check-more-types module using the following command.

npm install check-more-types --save

How to validate short git commit ID in JavaScript

In this section we show you how to use the check-more-types library shortCommitId() method to check if a given string is a valid 7 characters short SHA git commit ID value.

In the sample-project directory create a new file named check-short-commit-id.js as below.

check-short-commit-id.js

var check = require('check-more-types');

console.log(check.shortCommitId("20e0cb4"));
console.log(check.shortCommitId("4b85fa7"));
console.log(check.shortCommitId("test value"));
console.log(check.shortCommitId("1234567890"));

Run the check-short-commit-id.js file using the following command.

node check-short-commit-id.js
The output is:
true
true
false
false

More examples of how to use the check.shortCommitId() method

check-short-commit-id-example.js

var check = require('check-more-types');
var value1 = '595030e';
var value2 = 'fb9fd5b9dcafdfc325329a8d592590e5966c252d';

if(check.shortCommitId(value1)) {
    console.log(value1 + ' is a valid git short commit ID.');
} else {
    console.log(value1 + ' is an invalid git short commit ID.');
}

if(check.shortCommitId(value2)) {
    console.log(value2 + ' is a valid git short commit ID.');
} else {
    console.log(value2 + ' is an invalid git short commit ID.');
}

Run the check-short-commit-id-example.js file using the following command.

node check-short-commit-id-example.js
The output is:
595030e is a valid git short commit ID.
fb9fd5b9dcafdfc325329a8d592590e5966c252d is an invalid git short commit ID.

Happy Coding 😊