Comment créer un Captcha en JavaScript ?

Réponses rédigées par Antoine
Dernière mise à jour : 2022-07-12 11:01:37
Thèmes : javascript - captcha
Question

Pouvez vous me montrer comment créer un Captcha en JavaScript ?

Réponse

Pour créer un Captcha en JavaScript, vous devez concevoir deux fonctions :

  • Une fonction pour générer un code Captcha aléatoire.
  • Une fonction pour comparer le captcha à la saisie de l'utilisateur.

Voici un exemple pour créer un Captcha en JavaScript :

<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<title>Comment créer un Captcha en JavaScript ?</title>
<style>
.captcha {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
text-decoration: line-through underline overline #000;
}
</style>
<body>
<div id="captcha_image" class="captcha"></div>
<br>
<div style="cursor:pointer;" onclick="genererCaptcha()">Changer de captcha</div>
<br>
<input type="text" id="captcha_input" placeholder="Recopiez le code">
<input type="submit" onclick="affichermsg()">
<br>
<div id="resultat"></div>
<script>
var captcha;
var longueur_captcha = 6;

function genererCaptcha() {
document.getElementById("captcha_input").value = "";
captcha = document.getElementById("captcha_image");
var code_captcha = "";
const hasard = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  for (let i = 1; i < longueur_captcha; i++) {
    code_captcha += hasard.charAt(Math.random() * hasard.length);
  }
captcha.innerHTML = code_captcha;
}
 
function affichermsg() {
const captcha_input = document.getElementById("captcha_input").value;
  if (captcha_input == captcha.innerHTML) {
    var s = document.getElementById("resultat").innerHTML = "Captcha correct";
    genererCaptcha();
  }
  else {
    var s = document.getElementById("resultat").innerHTML = "Captcha incorrect";
    genererCaptcha();
  }
}

genererCaptcha();
</script>
</body>
</html>