0

我有一个评论表单,它使用 ajax 使用弹出菜单显示评论框,并且在提交评论时,评论被注册到适当的帖子(没有任何页面刷新)。我想在此表单中添加验证码。

我尝试实现以下生成一个小的随机数验证码的 javascript 代码。

<p>

      <label for="code">Write code below > <span id="txtCaptchaDiv" style="color:#F00"></span><!-- this is where the script will place the generated code -->

      <input type="hidden" id="txtCaptcha" /></label><!-- this is where the script will place a copy of the code for validation: this is a hidden field -->

      <input type="text" name="txtInput" id="txtInput" size="30" />

</p>

上面的 html 用于显示生成的验证码和一个文本输入,供用户输入代码。

以下是生成代码的 javascript 代码 -

<script type="text/javascript">
//Generates the captcha function    
    var a = Math.ceil(Math.random() * 9)+ '';
    var b = Math.ceil(Math.random() * 9)+ '';       
    var c = Math.ceil(Math.random() * 9)+ '';  
    var d = Math.ceil(Math.random() * 9)+ '';  
    var e = Math.ceil(Math.random() * 9)+ '';  

    var code = a + b + c + d + e;
    document.getElementById("txtCaptcha").value = code;
    document.getElementById("txtCaptchaDiv").innerHTML = code;  
</script>

下一个 javascript 代码用于验证验证码 -

<script type="text/javascript">
function checkform(theform){
    var why = "";

    if(theform.txtInput.value == ""){
        why += "- Security code should not be empty.\n";
    }
    if(theform.txtInput.value != ""){
        if(ValidCaptcha(theform.txtInput.value) == false){
            why += "- Security code did not match.\n";
        }
    }
    if(why != ""){
        alert(why);
        return false;
    }
}

// Validate the Entered input aganist the generated security code function   
function ValidCaptcha(){
    var str1 = removeSpaces(document.getElementById('txtCaptcha').value);
    var str2 = removeSpaces(document.getElementById('txtInput').value);
    if (str1 == str2){
        return true;    
    }else{
        return false;
    }
}

// Remove the spaces from the entered and generated code
function removeSpaces(string){
    return string.split(' ').join('');
}

</script>

此代码在不与评论表单结合使用时可以正常工作。在结合评论表单时,验证未完成。

对于基于 ajax 的评论表单,提交按钮在提交评论时传递一个隐藏的输入变量,该变量将其与相应的帖子相关联。这是我的评论部分的提交按钮代码 -

<button type="submit" class="comment-submit btn submit" id="submitted" name="submitted" value="submitted"><?php _e( 'Submit', APP_TD ); ?></button>

<input  type='hidden' name='comment_post_ID' value='<?php echo $post->ID; ?>' id='comment_post_ID' />

所以基本上我希望我的代码首先在评论表单的提交按钮上检查验证码值,如果正确,我只想使用 ajax 功能提交评论。

4

1 回答 1

0

仅将 Javascript 用于验证码并不是一个好主意。由于您的安全性仅在客户端完成。

您的解决方案是使用一种方法停止您的表单提交,并且仅当您的验证码函数返回 true 时,然后提交表单数据。这可以通过不同的方式完成,例如 jquery:

$('.comment-submit').click(function(e){
  e.preventDefault();
  if (ValidCaptcha()) {
    yourFormElement.submit();
  }
});
于 2013-10-17T16:30:32.153 回答