Create a captcha Valldation in HTML and Javascript
html
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>