1StopCoders

Code Examples and Industry News

ColdFusion Captcha with CFImage and Javascript Val

ColdFusion - Created by Casey Martin: 2014-05-10 20:15:00

This is the ColdFusion code that contains a textbox and captcha image. It uses the cfimage tag to generate the captcha image.



This Javascript function converts a string to hash.
hashCode = function(str){
    var hash = 0;
    if (str.length == 0) return hash;
        for (i = 0; i < str.length; i++) {
                char = str.charCodeAt(i);
                hash = ((hash<<5)-hash)+char;
                hash = hash & hash;
        }
    return hash;
}
This Javascript function validates the entered text against the text in the image.
document.getElementById('captchaHashJS').value = hashCode('#captcha#');
function verifyCaptcha() {
    var captchaHash = document.getElementById('captcha').value;
    captchaHash = captchaHash.toUpperCase();
    captchaHash = hashCode(captchaHash);
    
    var captchaHashJS = document.getElementById('captchaHashJS').value;

    if (captchaHash != captchaHashJS) {
        alert("The value you entered for the captcha is incorrect.");
        window.setTimeout(function () { 
            document.getElementById('captcha').focus(); 
        }, 0); 
        return false;
    }
}