javascript クレジットカードの番号であるかどうかを判定する

javascript クレジットカードの番号であるかどうかを判定する

javascriptで、クレジットカードの番号であるかどうかを判定するサンプルコードを記述してます。カートの種類により判定処理が異なりますが、全て使用することで判定することが可能です。

環境

  • OS windows11 pro 64bit
  • ブラウザ chrome 107.0.5304.122

クレジットカードであるかどうかを判定する

クレジットカードであるかどうかを判定するには、カードの種類ごとに正規表現を使用します。

カード名称開始番号桁数正規表現
 VISA413,16 ^4[0-9]{12}(?:[0-9]{3})?$
 MASTER Card510000〜559999, 222100〜27209916^(?:5[1-5][0-9]{2}|222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}$
 American Express34, 3716^3[47][0-9]{13}$
Diners Club300 – 303574, 3095, 36, 38 – 3915^3(?:0[0-5]|[68][0-9])[0-9]{11}$
Discover60110, 60112-60114, 601174 – 601179, 601186 – 601199, 644 – 649, 6516^6(?:011|5[0-9]{2})[0-9]{12}$
 JCB3528 – 358914^(?:2131|1800|35\d{3})\d{11}$

実際に、これらの正規表現を全て使用すると判定することが可能です。

let str = "378282246310005";

// クレジットカードチェック
if (str.match(/^(?:4[0-9]{12}(?:[0-9]{3})?|(?:5[1-5][0-9]{2}|222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|6(?:011|5[0-9]{2})[0-9]{12}|(?:2131|1800|35\d{3})\d{11})$/)) {
    // クレジットカード
    console.log("クレジットカードです");
} else {
    // クレジットカード以外
    console.log("クレジットカードではありません");
}

// クレジットカードです

サンプルコード

以下は、
「実行」ボタンをクリックすると、テキストフォームに入力された値がクレジットカードの番号であるかを判定して表示する
サンプルコードとなります。

※cssには「tailwind」を使用してます。関数はアロー関数を使用してます。

<!DOCTYPE html>
<html lang="ja">

<head>
    <meta charset="utf-8">
    <title>mebeeサンプル</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdn.tailwindcss.com"></script>
</head>

<script>

    window.onload = () => {

        btn.onclick = () => {
            txt.value.match(/^(?:4[0-9]{12}(?:[0-9]{3})?|(?:5[1-5][0-9]{2}|222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|6(?:011|5[0-9]{2})[0-9]{12}|(?:2131|1800|35\d{3})\d{11})$/) ? foo.innerHTML = "クレジットカードです" : foo.innerHTML = "クレジットカードではありません"
        }

    }

</script>

<body>
    <div class="container mx-auto my-56 w-64 px-4">

        <div id="sample" class="flex flex-col justify-center">

            <h1 class="font-semibold text-red-500 text-lg mr-auto">実行結果</h1>

            <p id="foo" class="font-semibold text-lg mr-auto"></p>

            <input
                class="mb-2 shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
                id="txt" type="txt">

            <button id="btn"
                class="mb-2 md:mb-0 bg-transparent hover:bg-red-500 text-red-700 font-semibold hover:text-white py-2 px-4 border border-red-500 hover:border-transparent rounded">
                実行
            </button>

        </div>

    </div>
</body>

</html>

判定されていることが確認できます。