Captcha Test

by bhatnagar018

HTML

<!DOCTYPE html>
<html>

  <body>

    <h2>HTML Forms</h2>

    <form onsubmit="mySubmit()">
      <label for="fname">First name:</label><br>
      <input type="text" id="fname" name="fname" value="John"><br>
      <label for="lname">Last name:</label><br>
      <input type="text" id="lname" name="lname" value="Doe"><br><br>
      <canvas id="myCanvas" width="300" height="30" style="border:1px solid grey;">
        Sorry, your browser does not support canvas.
      </canvas>
      <input type="text" id="captachValue" placeholder="captach value" />
      <button type="button" onclick="refresh()">
        Refresh
      </button>
      <input type="submit" value="Submit">
    </form>

  </body>

</html>

JavaScript

let result = 0;

function fillCaptach() {
  const canvas = document.getElementById("myCanvas");
  const firstNumber = Math.floor(Math.random() * 10) + 1;
  const secondNumber = Math.floor(Math.random() * 10) + 1;

  const ctx = canvas.getContext("2d");
  ctx.clearRect(0, 0, 300, 30);
  const text = `${firstNumber} + ${secondNumber}`;
  ctx.font = "24px Arial";
  ctx.fillText(text, 5, 22);
  result = firstNumber + secondNumber;
}

function refresh() {
  fillCaptach();
}

function mySubmit() {
  const val = document.getElementById('captachValue').value;
  if (result && result === Number(val)) {
    alert('valid captcha');
  } else {
    alert('Not a valid captcha');
    fillCaptach();
  }
  event.preventDefault();
}