[英]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.