How to Create Captcha using JavaScript

Captcha is a technique to protect web forms . Here is the code snippet to create Captcha in JavaScript.

  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <title>Using JavaScript how to Create Captcha</title>  
  5.     <script type="text/javascript">  
  6.         /* Function to Generat Captcha */  
  7.         function GenerateCaptcha() {  
  8.             var chr1 = Math.ceil(Math.random() * 10) + '';  
  9.             var chr2 = Math.ceil(Math.random() * 10) + '';  
  10.             var chr3 = Math.ceil(Math.random() * 10) + '';  
  11.   
  12.             var str = new Array(4).join().replace(/(.|$)/g, function () { return ((Math.random() * 36) | 0).toString(36)[Math.random() < .5 ? "toString" : "toUpperCase"](); });  
  13.             var captchaCode = str + chr1 + ' ' + chr2 + ' ' + chr3;  
  14.             document.getElementById("txtCaptcha").value = captchaCode  
  15.         }  
  16.   
  17.         /* Validating Captcha Function */  
  18.         function ValidCaptcha() {  
  19.             var str1 = removeSpaces(document.getElementById('txtCaptcha').value);  
  20.             var str2 = removeSpaces(document.getElementById('txtCompare').value);  
  21.   
  22.             if (str1 == str2) return true;  
  23.             return false;  
  24.         }  
  25.   
  26.         /* Remove spaces from Captcha Code */  
  27.         function removeSpaces(string) {  
  28.             return string.split(' ').join('');  
  29.         }  
  30.     </script>  
  31.   
  32. </head>  
  33. <body onload="GenerateCaptcha();">  
  34.     <div style="border: 2px solid gray; width: 700px;">  
  35.         <h2>Generating Captcha Demo</h2>  
  36.   
  37.         Enter the Captcha Text:  
  38.         <input type="text" id="txtCompare" />  
  39.         <input type="text" id="txtCaptcha" style="text-align: center; border: none; font-weight: bold; font-size: 20px; font-family: Modern" />  
  40.         <input type="button" id="btnrefresh" value="Refresh" onclick="GenerateCaptcha();" />  
  41.         <input id="btnValid" type="button" value="Check" onclick="alert(ValidCaptcha());" />  
  42.   
  43.         <br />  
  44.         <br />  
  45.     </div>  
  46. </body>  
  47. </html>