如何使用 php 验证输入字段


How to validate input field using php

我有一个联系表格,最后一个字段是防止垃圾邮件需要回答的数学问题。 检查它是否只有一个数字,没有其他字符的最佳方法是什么,答案应该是 15。还有可能,提交表格后如何使表格清楚?

网页代码:

<p id="math">10 + 5 =<input type="text" name="answerswerbox" id="answerswerbox" 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["answerswerbox"]); 
            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>';
            }
        }
        ?>

试试这个来检查计算问题:

if(!is_numeric($answerbox) || (int)$answerbox!=15){
    $errors[] = "Math answer is not correct.";
}

!is_numeric 检查它是否是数字。否则,消息将添加到错误数组中。如果是数字,则检查第二个条件。(int) 将变量转换为整数,因此您可以检查它是否为 15。

至于清除表单:由于您离开/重新加载页面,提交时表单不会自动清除吗?