How to create Captcha using JavaScript? – Client Side Captcha

twitter_capcha

Captcha is a technique to protect web forms from auto submission. Validating Captcha proofs that the user is a human. Today inside this growing network many hackers are sitting around the world. They have several tools to hack. Let’s talk about a simple login form. In a login form basically we have 2 input fields (username & password) with 1 submit button. To hack if we will pass random strings to username & password using a program there can be a chance in some point of time submit will successful. While manually it is quite difficult. That’s why Captcha.

Captcha is generating a code in the format of an image or string. User need to provide Captcha code before submitting a form. Here my intention to tell you adding Captcha reduce the chance of unnatural form submissions.

Captcha can be created at both the end server & client. In this example I created a Captcha using JavaScript at client-side. Client side Captcha helps to reduce more http requests. It gives better performance.

In the below code using math class I am generating 7 numeric characters randomly. Concatenating them with space in-between. Then assigning this value to txtCaptcha value. While user entering the text to txtCaptcha I am comparing these two values. If it is equal I am returning true else false.

Client Side Captcha

<!DOCTYPE html>
<html>
<head>
<title>Using JavaScript how to Create Captcha</title>
<script type="text/javascript">
/* Function to Generat Captcha */
function GenerateCaptcha() {
var chr1 = Math.ceil(Math.random() * 10)+ '';
var chr2 = Math.ceil(Math.random() * 10)+ '';
var chr3 = Math.ceil(Math.random() * 10)+ '';
var chr4 = Math.ceil(Math.random() * 10)+ '';
var chr5 = Math.ceil(Math.random() * 10)+ '';
var chr6 = Math.ceil(Math.random() * 10)+ '';
var chr7 = Math.ceil(Math.random() * 10)+ '';

var captchaCode = chr1 + ' ' + chr2 + ' ' + chr3 + ' ' + chr4 + ' ' + chr5 + ' '+ chr6 + ' ' + chr7;
document.getElementById("txtCaptcha").value = captchaCode
}

/* Validating Captcha Function */
function ValidCaptcha() {
var str1 = removeSpaces(document.getElementById('txtCaptcha').value);
var str2 = removeSpaces(document.getElementById('txtCompare').value);

if (str1 == str2) return true;
return false;
}

/* Remove spaces from Captcha Code */
function removeSpaces(string) {
return string.split(' ').join('');
}
</script>

</head>
<body onload="GenerateCaptcha();">
<h2>Generating Captcha Demo</h2>
<input type="text" id="txtCaptcha" style="text-align: center; border: none; font-weight: bold; font-family: Modern" />
<input type="button" id="btnrefresh" value="Refresh" onclick="GenerateCaptcha();" />
<input type="text" id="txtCompare" />
<input id="btnValid" type="button" value="Check" onclick="alert(ValidCaptcha());" />
</body>
</html>