Simple captcha written in JS. Check the comments in app.js for how to
$(document).ready(function () {
$( ".captcha" ).trigger("focus");
var range = [1,10] // range of captcha numbers. Can be anything but 1,10 is used for simplicity of calculations by the user
// function _displayCaptchaQuery has to be executed before check to keep the captcha set.
var query = _displayCaptchaQuery(range);
$('.submit').click(() => { _checkCaptchaQuery(query); });
});
// returns a random int between the bountries. Example _getRandomInt([1,20]) => 5, 16 .
var _getRandomInt =(min, max) => {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// produces a captcha set and stores it in an array. Example _makeCaptchaSet([1, 10]) => [3, 5, 8] -> 3+5 =8
var _makeCaptchaSet = (bountries) => {
var set = [];
var num1 = _getRandomInt(bountries[0], bountries[1]);
var num2 = _getRandomInt(bountries[0], bountries[1]);
var res = num1 + num2;
set.push(num1,num2,res);
return set;
}
// displays the current captcha set to the front end and returns it for use in _checkCaptchaQuery()
_displayCaptchaQuery = (bountries) => {
var queryTbl = _makeCaptchaSet(bountries);
$('.captchaQuery').text(queryTbl[0] + ' συν ' +queryTbl[1] + ' =');
return queryTbl;
}
//checks if the input matches the captcha set. Notifications are using alert but more functionality can be added here
var _checkCaptchaQuery = (set) => {
if($('.captcha').val() == set[2]) {
alert('correct');
return true;
}else {
alert('false captcha');
return false;
}
}
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<form name="captcha">
<label class="captchaQuery" for="captchaIn">3 + 5 ?</label>
<input required class="captcha" name="captchaIn" type="number" />
<button name="submit" role="submit" type="submit" class="submit">Check</button>
</form>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script src="simpleCaptcha.js"></script>
</body>
</html>