circuit

Build a Captcha Generator Using JavaScript




Do you still remember, a few years ago, verification method in some site using captcha. Captcha is a type of challenge-response test to check the user is human or robot. In this article, I want to build simple captcha verification method using JavaScript.

As we know, captcha is work in website, so a bit understanding of DOM will really helpful for reading this article. Let's do it.

Boilerplate

Here we need to initialize the program that consist index.html, style.css, and app.js. Yes, you can rename it as you want.

index.html

Code above, is the main program of the index.html, the output of the program is like this

Let skip the style.css and app.js right now, and go to the next step.

Main Algorithm

Here I want to build the main program. Captcha is consist of some string and the value is random. So, we need to build a function that can make some random string.

app.js

From the code above, we can know that I initialize new Array named captcha. After that, I build a function named createCaptcha. The function will generate some random value and will saved into captcha as an array. Lastly, I combined array of captcha into theCaptcha. So theCaptcha will become a random string.

Also, by using DOM, I use element captcha from index.html. And use it in the last line. To make the function work, I am adding script in index.html in line 12. The script is used for calling the createCaptcha function from app.js. Also I add onclick inside the line 14 to call createCaptcha function. Like this:

So, the output right now, will be like this.

Yeah, we can generate random string and also we can change the value, by clicking the Change text. But it's not done yet, we need to validate the output, so when we put wrong value in the input area and press submit, we will know, we put the right captcha or not. So we need to make new function, I named it ValidateCaptcha(). Here is the function:

From the code above, I use two elements that have id errCaptcha and reCaptcha from index.html. The reCaptcha is the input area and the errCaptcha is used for displaying message after user press the submit button. To check wether the input same with the captcha or not. So to make program work, we must add the function inside the Submit button in line 24. Like this:

Until now, the program will be like this. If we put wrong captcha it prompt that the captcha is wrong, and if the input is right the captcha is done.

Styling The Program

We can say, that our program is done right now. But we need to give some styling right? So, the program will be more beautiful. So, I put style.css like this:

style.css

The program will be like this, and you can edit it as you want.

I hope you enjoyed this article.

Happy Coding 😎




Continue Learning