Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

JavaScript Captcha Creation and Validation

2.40/5 (3 votes)
23 Feb 2021CPOL1 min read 9.9K  
Captcha creation and validation in JavaScript
This tip will help beginners in web development to add captcha to their developed web pages. It will also help learn how to create and validate captcha in JavaScript.

Background

CAPTCHA stands for Completely Automated Public Turing test to tell Computers and Humans Apart. In other words, CAPTCHA determines whether the user is real or a spam robot. CAPTCHAs stretch or manipulate letters and numbers, and rely on human ability to determine which symbols they are.

Captcha Verification is a common web technique used to help ensure that your respondents are real humans and not a program written to spam your survey. The respondent is asked to check a box to prove that she/he is human.

Using the Code

How Does It Work?

HTML
<input id="Button1" type="button" value="Check" onclick="CheckValidCaptch();"/>

Onclick Event of button invokes the CheckValidCaptcha() method, which in turn returns a boolean value, i.e., True/False.

CheckValidCaptcha() method compares the entered code in the textbox against the drawn or displayed code in the captcha box. RemoveSpaces(string) method removes the occurrence of any blank spaces within the created as well as entered code. After all, both the strings are compared by removing any blank spaces.

Based on the return value from CheckValidCaptcha, the result is displayed as either 'True' or 'False'. You can customize the return value to any user friendly message instead of true or false.

HTML
<input type="button" id="btnrefresh" value="Refresh" onclick="generateCaptcha();" />

generateCaptcha() method is invoked to draw a captcha on the screen. On click of Refresh button, we can generate/draw the new captcha images.

HTML
<body onload="generateCaptcha();">

On body load, I am calling generateCaptcha() method so that whenever the page is loaded, the default captcha should be drawn.

Points of Interest

The detailed source code is as follows:

XML
<html>
   <head>
      <script type="text/javascript">
         function generateCaptcha()
         {
             var alpha = new Array('A','B','C','D','E','F','G','H','I','J','K','L','M',
                                   'N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
                                   'a','b','c','d','e','f','g','h','i','j','k','l','m',
                                   'n','o','p','q','r','s','t','u','v','w','x','y','z');
             var i;
             for (i=0;i<4;i++){
               var a = alpha[Math.floor(Math.random() * alpha.length)];
               var b = alpha[Math.floor(Math.random() * alpha.length)];
               var c = alpha[Math.floor(Math.random() * alpha.length)];
               var d = alpha[Math.floor(Math.random() * alpha.length)];
              }
            var code = a + '' + b + '' + '' + c + '' + d;
            document.getElementById("mainCaptcha").value = code
          }
          function CheckValidCaptcha(){
              var string1 = removeSpaces(document.getElementById('mainCaptcha').value);
              var string2 = removeSpaces(document.getElementById('txtInput').value);
              if (string1 == string2){
         document.getElementById('success').innerHTML = "Form is validated Successfully";
         //alert("Form is validated Successfully");
                return true;
              }
              else{      
         document.getElementById('error').innerHTML = "Please enter a valid captcha.";
         //alert("Please enter a valid captcha.");
                return false;        
              }
          }
          function removeSpaces(string){
            return string.split(' ').join('');
          }
      </script>   
   </head>
   <body onload="generateCaptcha();">
      <center>
         <h1>Please please fill the following fields to validate.</h1>
         <table>
            <tr>
               <td>
               </td>
            </tr>
            <tr>
               <td>
                  <input type="text" 
                  id="mainCaptcha"readonly="readonly"/> //set background image 
                                                        //according to your choice.
                  <input type="button" 
                  id="refresh" value="Refresh" onclick="generateCaptcha();" />
               </td>
            </tr>
            <tr>
               <td>
                  <input type="text" id="txtInput"/>   
               </td>
            </tr>
            <tr>
               <td>
                  <input id="Button1" type="button" 
                  value="Check" onclick="CheckValidCaptcha();"/>
               </td>
            </tr>
            <tr>
               <td><span id="error" style="color:red"></span></td>
            </tr>
            <tr>
               <td><span id="success" style="color:green"></span></td>
            </tr>
         </table>
      </center>
   </body>
</html>

History

  • 23rd February, 2021: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)