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

In this JavaScript tutorial we learn how to check whether a given string is a valid 40 digit 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 git commit ID in JavaScript

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

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

check-git-commit-id.js

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

console.log(check.commitId('0fb33895f65e226043fea311ac6498120a4780a3'));
console.log(check.commitId('360391f7d98459f437d27203b2f7dd165722849b'));
console.log(check.commitId('test string'));
console.log(check.commitId('f437d27203b'));

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

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

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

check-git-commit-id-example.js

var check = require('check-more-types');
var value1 = '0fb33895f65e226043fea311ac6498120a4780a3';
var value2 = 'f437d27203b'

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

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

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

node check-git-commit-id-example.js
The output is:
0fb33895f65e226043fea311ac6498120a4780a3 is a valid commit ID
f437d27203b is an invalid commit ID

Happy Coding 😊