Create a captcha Validation in HTML and Javascript

Posted By : Sudhir Kumar Ojha | 30-Jun-2017

Hi I am going to explain you how can put validation in form using javascript onsubmit. This is the client side validation on form. In this tutorial you can get captcha[Security Code] validation and you can also check email validation.

 

Captcha is an image with a code written on it. The website visitor is required to read the code on the image and enter the value in a text field. If the word entered is wrong, the form submission is not processed and will displays a error message. As CAPTCHA is a smartly blurred image, the spam bot can’t read it. So the form cannot be auto-submitted.

 

Here is the code:

 

 

<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>

 

How does it Works?

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

 

Onclick Event of button we are invoking the CheckValidCaptcha() method. Which in turns returns an boolean value i.e. True/False.

 

CheckValidCaptcha() Method compare's the entered code in the text box aganist the drawn or displayed code in the captcha box. RemoveSpaces(string) Method repoves the occurance of any blank spaces within the created as well as entered code. After all the both the strings are compared by removing any blank spaces.

 

Based on the return value fron 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.

 

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

 

generateCaptcha() Method is invoked to draw an captcha on the screen. On Click of refresh button we can generate/draw the new captcha images.

 

<body onload="generateCaptcha();">

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

 

Here we go, Save the HTML page and open in the web browser

 

Output is below:

 

 

 

About Author

Author Image
Sudhir Kumar Ojha

Sudhir Kumar Ojha is having skills to work as Software developer & having good knowledge of Java.

Request for Proposal

Name is required

Comment is required

Sending message..