JavaScript Captcha Example

In this tutorial you will get JavaScript captcha example.

Captcha is used to determine whether or not the user that is filling and submitting a web form is human. While developing web projects we often require to add captcha feature.

So here I have shared the simplest way to create captcha in JavaScript. It will look like as shown in below image.

Note: Don’t use this method in live web projects because this implementation is already readable by attacker and he/she can manipulate it. Everything should be processed on server side. You can just use this captcha generation method in your school or college projects.

JavaScript Captcha Example

JavaScript Captcha Example

The below code generates a 4 digits captcha in JavaScript.

 

Explanation

In above script the generateCaptcha() function is used to generate the captcha as the page loads. This is done by the onload attribute in body tag. Inside generateCaptcha() we have used Math.floor((Math.random() * 10)) to generate a random number between 1 (included) and 10 (excluded). In this way we generate four random numbers and then join them to form a string. The toString() method is used to convert number to string. Now we set this string as value of captcha textbox.

When Submit button is clicked the check() function is called that checks whether the entered captcha matches with original captcha or not. If they match, “Equal” alert is displayed otherwise “Not Equal” alert is displayed.

The Refresh button is used to regenerate the captcha.

The above JavaScript captcha code is easy to understand, still if you are facing any problem then comment below.

4 thoughts on “JavaScript Captcha Example

  1. Waqas Ali

    nice tutorial and explain very simple waiting more tutorial like this

    Reply
  2. Permil Garg

    This is not use practically. Because any software can read text by OCR and type.

    Reply
    1. Admin Post author

      Yes Permil you are right, this method must not be used in live projects. Everything should be processed on the server, otherwise anyone can get access to code and manipulate it.

      Reply
  3. mahesh

    hiii after entering wrong captcha i want 2 refresh it plz send me the code for it

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *