0

I've a contact form, and the last field is a math question to be answered from preventing spam emails. what is best way to check if its only a number, no other characters, & answer should be 15. Also ff possible, how make the form clear after its been submitted?

HTML code:

<p id="math">10 + 5 =<input type="text" name="answerbox" id="answerbox" value="<?= isset($_POST['answerbox']) ? $_POST['answerbox'] : '' ?>"/></p>

I've tried using ctype_digit function, but no luck, didn't work.

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

Full php code:

<?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>';

            }
        }
        ?>
4

1 回答 1

1

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

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

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

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

于 2013-09-21T14:55:42.130 回答