[英]captcha validation in php using javascript
我有一个评论表单,该表单使用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功能提交评论。
仅将Javascript用于验证码不是一个好主意。 由于您的安全性仅在客户端完成。
您的解决方案是使用一种方法来停止提交表单,并且仅当您的验证码函数返回true时,才提交表单数据。 这可以通过不同的方式完成,例如jquery:
$('.comment-submit').click(function(e){
e.preventDefault();
if (ValidCaptcha()) {
yourFormElement.submit();
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.