6碼驗證碼

0與O、數字1與小寫字母l、大寫字母i,容易造成使用者混淆,來源字串中應移除。

html

<body>

    <div align="center">

      <h1>隨機抽簽1到9號不重複+產生驗證碼</h1>

      <label id="number" style="color: #ff0000;font-size: 36px;">抽到的數字</label><br>

      <button id="send" style="color: #0000ff;font-size: 30px;" onclick="getRandomNumbers(4)">抽籤</button><br>

      <label id="result" style="font-size: 20px;"></label><br>

      <button id="captcha" style="color: #00abff;font-size: 30px;" onclick="generateCaptcha(6)">產生驗證碼</button><br>

      <label id="captchaCodes" style="font-size: 20px;">必須包含數字與大寫英文字母</label>

    </div>

</body>

重複,含0與O。

function generateCaptcha() {

    const length = 6;

    const characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';

    let captchaCode = '';


    for (let i = 0; i < length; i++) {

        const randomIndex = Math.floor(Math.random() * characters.length);

        captchaCode += characters.charAt(randomIndex);

    }


    const captchaElement = document.getElementById('captchaCodes');

    captchaElement.textContent = captchaCode;

}

不重複,不含0與O。

function generateCaptcha(codes) {

    const length = codes;

    const characters = '123456789ABCDEFGHIJKLMNPQRSTUVWXYZ';

    let captchaCode = '';


    while (captchaCode.length < 6){

      const randomIndex = Math.floor(Math.random() * characters.length);

      var tmpChar = characters.charAt(randomIndex);

      var exist = false;

      for (var i=0; i<captchaCode.length ;i++){

        if (tmpChar===captchaCode.charAt(i)){

          exist = true;

          break;

        }

      }

      if (!exist){

        captchaCode += tmpChar;

      }

    }


    const captchaElement = document.getElementById('captchaCodes');

    captchaElement.textContent = captchaCode;

}