A propósito de uma necessidade específica que sentimos em forum.semmais.com escrevi este pequeno módulo em JavaScript, tendo como objectivo diferenciar entre computadores e humanos.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 | /* Script Name: AntiSpamMath Script Version: 1.1 Script Date: 28/March/2009 Author Name: Paulo A. Silva Author Email: pauloasilva[at]gmail[dot]com Author Website: http://www.pauloasilva.com */ function ASMath(ApplyTo) { this.FormID = ApplyTo; this.operand1 = null; this.operand2 = null; this.answer = null; this.SetOperands(); this.SetAnswer(); this.SetForm(); } ASMath.prototype.SetOperands = function() { this.operand1 = Math.floor(Math.random() * 11); this.operand2 = Math.floor(Math.random() * 11); this.answer = this.operand1 + this.operand2; } ASMath.prototype.SetAnswer = function() { var bits = []; var dividend = parseInt(this.answer); var remainder = 0; while (dividend >= 2) { remainder = dividend % 2; bits.push(remainder); dividend = (dividend - remainder) / 2; } bits.push(dividend); bits.reverse(); this.answer = bits.join(""); document.getElementById("ASMathA").value = this.answer; } ASMath.prototype.VerifyAnswer = function() { var Answer = document.getElementById("ASMathQ"); return Answer.value == this.operand1 + this.operand2; } ASMath.prototype.SetForm = function() { var Form = document.getElementById(this.FormID); var Field = document.getElementById("ASMathQ"); var Me = this; Field.value = Me.operand1 +' + '+ Me.operand2 +' = ?'; Form.onsubmit = function() { if (!Me.VerifyAnswer()) { alert("Are you sure you're human?\nDon't be shy, use your fingers!"); return false; } return true; } Field.onfocus = function() { this.value = ""; } Field.onblur = function() { if(this.value == "") { Me.SetOperands(); Me.SetAnswer(); Field.value = Me.operand1 +' + '+ Me.operand2 +' = ?'; } } } |
A integração num form HTML é bastante simples, merecendo mesmo assim um exemplo:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <html>
<head>
<title>Demo</title>
<script language="JavaSript" type="text/javascript" src="AntiSpamMath_V2.js">
</script>
</head>
<body>
<form id="ASMathF" name="demo" action="demo" method="post">
<input id="ASMathQ" type="text" name="ASMathQ" />
<input id="ASMathA" type="hidden" name="ASMathA" />
<input id="ASMathB" type="submit" name="Submit" value="Ok" />
</form>
<script type="text/javascript">
var ASMath = new ASMath('ASMathF');
</script>
</body>
</html> |
O código está disponível ao abrigo da licença Creative Commons by-nc-sa 2.5 Portugal podendo fazer o download a partir daqui: AntiSpamMath
Nota: Embora funcional, o campo “ASMathA” não estava a ser preenchido pelo que o código fonte foi actualizado.
