jQuery form validation problem
I'm using the following code (via 'Dark Side of the Carton') to validate a reCAPTCHA field, before submitting the rest of a form that includes the captcha field.
The validation works fine, the 'recaptchavalidate' page is called, returns True or False correctly and the JavaScript picks this all up (I test this via alert(html);).
However, when True, the form doesn't continue to be sumbitted as you would expect. In fact, even worse, the reCAPTCHA refreshes as if the response was wrong.
I think it's my JavaScript at fault rather than the reCAPTCHA ... but where am I going wrong?
<script type="text/javascript">
$(function(){
function validateCaptcha()
{
challengeField = $("input#recaptcha_challenge_field").val();
responseField = $("input#recaptcha_response_field").val();
// alert(challengeField);
// alert(responseField);
//return false;
var html = $.ajax({
type: "POST",
url: "recaptchavalidate",
data: "recaptcha_challenge_field="+challengeField+ "&recaptcha_response_field="+responseField,
async: false
}).responseText;
if(html == "True")
{
$("#captchaStatus").html(" ");
alert(html);//test
return true;
开发者_开发百科 }
else
{
$("#captchaStatus").html("Your captcha is incorrect. Please try again");
alert(html);//test
Recaptcha.reload();
return false;
}
}
$("#signup").submit(function(){
return validateCaptcha();
});
});
</script>
EDIT: This is used only to check there are no errors before submitting. The reCAPTCHA is checked properly after submitting (via Python, not JS). So is not as big a security hole as some users have pointed out.
It seems that your test of html == "True"
isn't passing. Are you sure that that is the exact string you're getting back is "True"
with no extra characters/whitespace? If there is whitespace on the beginning or the end of the string, for example, the pass will fail but it will still look like "True" if you show the text via an alert box.
Try trimming whitespace from the end of the string by using this check instead:
if (html.replace(/^\s+|\s+$/, '') == "True")
Instead of alerting "html", hard-code "true" and "false" so you're sure it's getting to the correct spot.
if(html == "True")
{
$("#captchaStatus").html(" ");
alert("true");//test
return true;
}
else
{
$("#captchaStatus").html("Your captcha is incorrect. Please try again");
alert("false");//test
Recaptcha.reload();
return false;
}
Then report back with your findings.
I can't wait to encounter this in real world. :)
Then I will hack your javascript and just replace validateCaptcha()
with
function validateCaptcha() {
return true;
}
精彩评论