我有一个联系表单,最后一个字段是一个数学问题,可以通过阻止垃圾邮件来回答。什么是最好的方法来检查它是否只是一个数字,没有其他字符,&答案应该是15.也可以,如何使表格在提交后明确?
HTML code:
<p id="math">10 + 5 =<input type="text" name="answerbox" id="answerbox" value="<?= isset($_POST['answerbox']) ? $_POST['answerbox'] : '' ?>"/></p>
我尝试过使用ctype_digit函数,但没有运气,没有用。
if(ctype_digit($answerbox != 15) === true){
$errors[] = "Math answer is not correct.";
}
完整的PHP代码:
<?php
if(empty($_POST) === false) {
$errors = array();
$name = trim($_POST["name"]);
$email = trim($_POST["email"]);
$subject = trim($_POST["subject"]);
$message = trim($_POST["message"]);
$answerbox = trim($_POST["answerbox"]);
if(empty($name) === true || empty($email) === true || empty($subject) === true || empty($message) === true || empty($answerbox) === true){
$errors[] = '<p class="formerrors">Please fill in all fields.</p>';
} else {
if (strlen($name) > 25) {
$errors[] = 'Your name is too long.';
}
if (ctype_alpha($name) === false) {
$errors[] = "Your name only should be in letters.";
}
if(!preg_match("/^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$/i", $email)){
$errors[] = "Your email address is not valid, please check.";
}
if($answerbox != 15){
$errors[] = "Math answer is not correct.";
}
if(empty($errors) === true) {
$headers = 'From: '.$email. "\r\n" .
'Reply-To: '.$email . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail('me@mymail.me',$subject,$message,$headers);
print "<p class='formerrors'>Thank you for your message, I'll get back to you shortly!</p>";
}
}
}
?>
<?php
if (empty($errors) === false){
foreach ($errors as $error) {
echo'<p class="formerrors">', $error, '</p>';
}
}
?>
答案 0 :(得分:1)
请尝试检查calc问题:
if(!is_numeric($answerbox) || (int)$answerbox!=15){
$errors[] = "Math answer is not correct.";
}
!is_numeric检查它是否为数字。如果不是,则将消息添加到errors数组中。 如果是数字,则检查第二个条件。 (int)将变量转换为整数,因此您可以检查它是否为15。
至于清除表格:提交时是否自动清除表格,因为您离开/重新加载页面?