drus40229 2014-01-03 01:23
浏览 44
已采纳

PHP preg_match表单验证

I am having difficulties with my php code which validates the form on the page itself before sending out to my email.

This is my PHP which is above the doctype html

<?php
$name = $_POST['name'];
$email = $_POST['email'];
$subjectTitle = $_POST['subjectTitle'];
$comment = $_POST['comment'];   
$errormsg = "Invalid Entry";
$validmsg = "Thank you for your message";

if($_POST['submit']) {  
    if(empty($_POST['name'])) {     
        $nameError = true;  
    } 
    if(empty($_POST['email'])) {        
        $emailError = true; 
    }       
    if(empty($_POST['subjectTitle'])) {     
        $subjectError = true;   
    }       
    if(empty($_POST['comment'])) {
        $commentError = true;   
    } 
    else if (empty($_POST['name']) || empty($_POST['email']) || empty($_POST['subjectTitle']) || empty($_POST['comment'])) {    
        $error = true;      
    }               
    else {          
        $to = "EMAIL_ADD_GOES_HERE";        
        $name = trim($_POST['name']);
        $email = trim($_POST['email']);
        $subjectTitle = trim($_POST['subjectTitle']);
        $comment = trim($_POST['comment']);         
        $subject = "Contact Form Enquiry";          
        $messages = "
 Name: $name 
 Email: $email 
 Subject: $subjectTitle 
 Comments: $comment";
        $headers = "From:" . $name;
        $mailsent = mail($to, $subject, $messages, $headers);       
        if($mailsent) {         
            $sent = true;   
            $name = "";        
            $email = "";
            $subjectTitle = "";
            $comment = "";                          
        }           
    }   
}
?>

and for my HTML , to make viewing easier, I'll just put in the form part.

<html>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
     Name: <input type="text" name="name" id="name" value="<?php echo $name; ?>"> 
     <?php if($nameError == true) {echo $errormsg;} ?>

     Email: <input type="text" name="email" id="email" value="<?php echo $email; ?>"> 
     <?php if($emailError == true) {echo $errormsg;} ?>

     Subject: <input type="text" name="subjectTitle" id="subjectTitle" value="<?php echo $subjectTitle; ?>"> 
     <?php if($subjectError == true) {echo $errormsg;} ?>

     Comments: <textarea name="comment" id="comment"><?php echo $comment; ?></textarea>
     <?php if($commentError == true) {echo $errormsg;} ?>
</form>
</html>

There is no other php code in my html other than stated above.

This validation only works if any field is left empty. It will prompt the error msg within the page itself and would NOT send in the email, which is how it should work..

However, I am facing a weird problem which I can't seem to find out the reason/theory/logic behind it. If u look at the php code, if I didn't have that else if statement

else if (empty($_POST['name']) || empty($_POST['email']) || empty($_POST['subjectTitle']) || empty($_POST['comment'])) {        
    $error = true; 
}

the validation fails and will still send in an email when the user keys in the textarea. For example, if the user doesn't fill in the Name, Email and Subject but only the Comments, it will still get sent. However, once i put that else if statement, it fixes the problem.

But the main problem is, preg_match. I want the name fields to allow only space and letters and I want email field to only allow emails. So when I tried to put this code in,

if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
     $nameError = true;
}

or by combing it with the name empty field check

if (empty($_POST['name']) || (!preg_match("/^[a-zA-Z ]*$/",$name))) {
    $nameError = true;      
} 

it doesn't validate correctly. What it does is that, when a user enters a number into the name field and also fills up everything else, it will display error message and also the thank you message and send it to the email, which is not how it should work.

So can I have guidance on how to correct the problem? Is my coding done wrongly and also I would like to know why that else if statement which I have in php makes no sense yet I need that to get the proper validation.

Thank you so much for reading, been stuck on this for the past 6 days and I really dont know how to fix this. Please help me.

Cheers

  • 写回答

3条回答 默认 最新

  • dongxun6690 2014-01-03 01:40
    关注

    Try this.

    I've made the following changes:

    • Trim the values before validating.
    • Use the variables that were assigned from $_POST in the validation checks.
    • Use a single $error variable that I append errors to.
    • Use + instead of * in the regular expression, so it won't match an empty value, and we don't need an explicit empty() check. Also use the i modifier to make it case-insensitive, instead of A-Za-z.
    • And the most important part: I fixed the else if logic at the end. You were only doing all the empty() checks if the comment wasn't empty.
    <?php
    $name = trim($_POST['name']);
    $email = trim($_POST['email']);
    $subjectTitle = trim($_POST['subjectTitle']);
    $comment = trim($_POST['comment']);
    
    $errormsg = "Invalid Entry";
    $validmsg = "Thank you for your message";
    $error = '';
    
    if($_POST['submit']) {
    
        if(!preg_match('/^[a-z ]+$/i', $name)) {
            $error .= 'Name missing or incorrect<br>';
        } 
    
        if(empty($email)) {
            $error .= 'Missing email<br>';
        }
    
        if(empty($subjectTitle)) {
            $error .= 'Missing title<br>';
        }
    
        if(empty($comment)) {
            $error .= 'Missing comment<br>';
        }
    
        if ($error) {
            echo $error;       
        } else {
            $to = "EMAIL_ADD_GOES_HERE";
    
            $subject = "Contact Form Enquiry";
    
            $messages = "
     Name: $name 
     Email: $email 
     Subject: $subjectTitle 
     Comments: $comment";
            $headers = "From:" . $name;
            $mailsent = mail($to, $subject, $messages, $headers);
    
            if($mailsent) {
    
                $sent = true;
    
                $name = "";        
                $email = "";
                $subjectTitle = "";
                $comment = "";
    
            }
    
        }
    
    }
    
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题