检查输入值是否不等于整数然后不提交表单
我有一个简单的PHP电子邮件表单,但我收到垃圾邮件。 我添加了一个检查输入,用户必须填写输入。 如果输入值等于12则提交表单,否则不提交弹出错误的表单。(请做数学。)
我在下面使用php方法:
if(isset($_POST['not_robot']) !== 12 && isset($_POST['not_robot']) !== ''){ echo 'alert("Please do the math, if you are human.");'; }else{ //email script here }
当我提交表单时,错误弹出显示“请做数学,如果你是人”,但在我关闭弹出窗口后,它也会发送电子邮件。 任何帮助appreaciated谢谢
PS:如果使用javascript或jquery可以检查方法,那将是一个很好的帮助。
尝试检查提交表单的时间。 使用以下代码或链接 –
的jsfiddle
HTML代码 –
JAVASCRIPT代码 –
$('form').submit(function() { if (parseInt($('input[name="not_robot"]').val()) == 12) { return true; } else{ alert('You not enterd the correct value'); return false; } });
您需要在客户端上进行测试:
简单JS
window.onload=function() { document.querySelector("form").onsubmit=function(e) { var val = this.elements["not_robot"].value; return !isNaN(val) && parseInt(Number(val)) == val && !isNaN(parseInt(val, 10); } }
jQuery的:
$(function() { $("form").on("submit",function(e) { var val = $("[name='not_robot'"].val(); if (isNaN(val) || !parseInt(Number(val)) == val || isNaN(parseInt(val, 10)) e.preventDefault(); } }
不要试图阻止以这种方式发送垃圾邮件。 我的建议是应用csrf保护和谷歌validation码。 您可以使用此库进行csrf保护。 对于谷歌validation码使用这个
如果你想通过PHPvalidation..Below就是这样
if(is_numeric($_POST['not_robot']) && !empty($_POST['not_robot'])){ echo ''; }else{ //email script here }
方法 :
-
使用PHP exit()函数退出当前脚本执行。我们可以使用此函数(或不使用)消息。
语法:
exit(message)
OR
exit()
-
我们也可以使用
return;
此处,控件将返回调用该文件运行的脚本。
试试这个 :
if(isset(($_POST['not_robot']) != '12') && (isset($_POST['not_robot']) !== '')){ /* alert here */ exit(); }else{ //email script here }
HTML:
javascipt的:
function checkForm() { if(document.getElementById('not_robot').value == "12" && document.getElementById('not_robot').value != "") { alert('ok'); document.forms['form1'].submit(); }else{ alert('not ok'); } }