.NET 1.1项目中的Recaptcha Validator

时间:2010-03-31 20:33:00

标签: .net validation .net-1.1 recaptcha

我正在尝试在.net 1.1项目中使用旧版本的Recaptcha Validator,可在此处找到:http://recaptcha.googlecode.com/svn/trunk/recaptcha-plugins/dotnet-old/src/Recaptcha/

我所拥有的代码与上述链接中的示例非常相似:

<asp:TextBox ID="EmailAddress" runat="server"></asp:TextBox>
<recatpcha:RecaptchaValidator ID="RecaptchaValidator1" runat="server" Theme="Clean" PublicKey="xxxxxxxxxxxxxx" PrivateKey="xxxxxxxxxx" ControlToValidate="EmailAddress"></recatpcha:RecaptchaValidator>
<asp:Button ID="Button1" runat="server" Text="Button" CausesValidation="true" OnClick="Button1_Click" />

我想要的行为很简单:在页面加载时,会向用户显示一个输入其电子邮件地址的字段,一个要完成的验证码以及一个提交按钮。在提交时,如果在我们的数据库中找不到具有该电子邮件地址的用户,或者验证码被错误地回答,则会显示新的验证码以及相应的错误消息。否则,他们将收到有关如何重置密码的电子邮件。

主要问题是验证码不会在页面加载时显示。但是,当我按下提交按钮时,触发Page.Validate(),页面将被重新加载并显示验证码。

基于此,我想我会尝试一种不同的方法并在页面加载事件中调用Page.Validate()来使得验证码最初显示出来。这几乎起作用:验证码出现在第一页加载,但是当提交无效的电子邮件以及正确的验证码答案时,验证码在页面重新加载时消失,但当然,电子邮件无法发送。

如何在最初点击页面时强制显示验证码,或者在输入无效的电子邮件地址时阻止验证码的提交?

1 个答案:

答案 0 :(得分:1)

嗯,它并不漂亮,但我让它发挥作用。

由于使用RecaptchaValidator标签不能按照我想要的方式工作,因此我使用了recaptcha AJAX API(http://recaptcha.net/apidocs/captcha/client.html)将小部件嵌入到页面中:

$(document).ready(function() {
    Recaptcha.create("<public key>",
        "ReCaptcha", {
        theme: "clean",
        callback: Recaptcha.focus_response_field
    });
});

然后,由于所有数据都需要使用recaptcha服务器验证(质询,公钥等等,这里有更多信息:http://recaptcha.net/apidocs/captcha/)在POST中,我实例化了一个新的RecaptchaValidator,设置了剩余的属性,并且调用验证用户响应的方法。

protected void Submit_Click(object sender, System.EventArgs e) 
{
    RecaptchaValidator RecaptchaValidator1 = new RecaptchaValidator();
    RecaptchaValidator1.Page = this;
    RecaptchaValidator1.PrivateKey = "<private key>";
    RecaptchaValidator1.PublicKey = "<public key>";

    bool CaptchaPassed = RecaptchaValidator1.ValidateUserResponse();

    if (CaptchaPassed)
    {    
        //hide the captcha, do some stuff
    }       
}

不可否认有点hacky,但它完成了工作。

注意 - 我在问题中提到了这一点,但只是重申:服务器端代码使用旧的.NET 1.1兼容的recaptcha插件。插件代码的链接就在问题中。我有令人尴尬的低代表,并且不能使用任何更多的超链接&gt;。&lt;