简体   繁体   English

使用'if'的PHP表单验证

[英]PHP Form validation using 'if'

I'm currently building a very small 'contact' form for use on a personal site. 我目前正在建立一个非常小的“联系”表单,用于个人网站。

The form works, and each validation 'if' statement works individually, however, if for example I input a valid email address and phone number but leave the message blank, the email still sends and I get the success message. 该表格有效,每个验证“ if”语句均单独起作用,但是,例如,如果我输入了有效的电子邮件地址和电话号码,但将该消息保留为空白,则该电子邮件仍会发送,并且我会收到成功消息。

My guess would be to include the small 'if' statements into the one checking whether my required fields are not empty, though i'm not sure how to do this correctly as it is nesting multiple 'if's into one. 我的猜测是将小的“ if”语句包含在其中,以检查我的必填字段是否为空,尽管我不确定如何正确执行此操作,因为它会将多个“ if”嵌套到一个。

Cheers 干杯

<?php 
            // Validation goes here
            $errors = '';
            $success = 'Success! Your message has been sent. You should receive a reply within 48 hours.';

            $email = $_POST['email']; 
            $name = $_POST['thename']; 
            $comments = $_POST['comments'];
            $number = $_POST['number']; 

            if(empty($name) || empty($email) || empty($comments)) {
                $errors .= "Error: please input a name, email address and your message.";
            } else {
                $errors = '';
            }

            if (!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $email)) {
                $errors .= "Error: Invalid email address";
            } else {
                $errors = '';
            }

            if (!preg_match("/^\(?0( *\d\)?){9,10}$/", $number)) {
                $errors .= "Error: Invalid phone number";
            } else {
                $errors = '';
            }

        ?>

        <!-- Display red error box or green success box depending on which is true -->
        <?php if(!empty($errors)): ?>
            <div class="validationbox | errorsbox">
                <?php echo $errors; ?>
            </div>
        <?php elseif(empty($errors)): ?>
            <div class="validationbox | successbox">
                <?php echo $success; ?>
            </div>
            <?php 
                $message = ''; // Blank message to start with so we can append to it.

                // Construct the message
                $message .= "
                    Name: {$_POST['thename']};
                    Email: {$_POST['email']};
                    Number: {$_POST['number']};
                    Enquiry-type: {$_POST['enquiry-options']};
                    Message: {$_POST['comments']};
";
                // test@testdomain.com
                $to = 'test-email-deleted-for-stackoverflow'; 
                $subject = 'Message from Portfolio';
                $from = $_POST['thename'];
                // YourSite@domain.com
                $fromEmail = 'test-email-deleted-for-stackoverflow';
                $header = 'From: ' . $from . '<' . $fromEmail . '>';
                mail($to,$subject,$message,$header);
            ?>
        <?php endif; ?>
    <?php endif; ?>

Based on the information Supplied, i think you should use a complex if-elseif-else statement like so: 根据提供的信息,我认为您应该使用如下复杂的if-elseif-else语句:

`if (condition) {
    code to be executed if this condition is true;
} elseif (condition) {
    code to be executed if this condition is true;
} else {
    code to be executed if all conditions are false;
} `

in your particular case: 在您的特定情况下:

// Validation goes here
                $errors = '';
                $success = 'Success! Your message has been sent. You should receive a reply within 48 hours.';

                $email = $_POST['email']; 
                $name = $_POST['thename']; 
                $comments = $_POST['comments'];
                $number = $_POST['number']; 

                if(empty($name) || empty($email) || empty($comments)) {
                    $errors .= "Error: please input a name, email address and your message.";
                } elseif(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $email)) {
                    $errors = 'Error:invalid email';
                }elseif(!preg_match("/^\(?0( *\d\)?){9,10}$/", $number){
                    $errors .= "Error: Invalid phone number";

                } else {
                    //Do this on successful validation comes here
                }

Your problem is that you are resetting $errors back to '' each time one of your validation conditions passes: 您的问题是,每次通过验证条件之一时,您都将$errors重新设置为''

        if(empty($name) || empty($email) || empty($comments)) {
            $errors .= "Error: please input a name, email address and your message.";
        } else {
            $errors = '';
        }

        if (!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $email)) {
            $errors .= "Error: Invalid email address";
        } else {
            $errors = '';
        }

        if (!preg_match("/^\(?0( *\d\)?){9,10}$/", $number)) {
            $errors .= "Error: Invalid phone number";
        } else {
            $errors = '';
        }

You shouldn't do that, just leave error messages to whatever it previously was. 您不应该这样做,只需将错误消息保留为以前的状态。 This way, when you get to the end, $errors will contain a string of all the error messages combined. 这样,当您到达最后时, $errors将包含所有错误消息组合而成的字符串。 Since there could be multiple messages, you may want to put a break a the end of each one: 由于可能会有多条消息,因此您可能需要在每条消息的结尾处加一个中断:

        if(empty($name) || empty($email) || empty($comments)) {
            $errors .= "Error: please input a name, email address and your message.<br>";
        } 

        if (!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $email)) {
            $errors .= "Error: Invalid email address<br>";
        } 

        if (!preg_match("/^\(?0( *\d\)?){9,10}$/", $number)) {
            $errors .= "Error: Invalid phone number<br>";
        }

In the case of email, you may want to only display the 'invalid email address' only when something was actually filled in, so you could also check to ensure there is something in there, before you determine if the format is valid or not: 对于电子邮件,您可能只想在实际填写内容时才显示“无效的电子邮件地址”,因此在确定格式是否有效之前,您还可以检查以确保其中有内容:

    if (!empty($email) && !preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $email)) {

try below code it helps you. 试试下面的代码,它可以帮助您。

<?php 
            // Validation goes here
            $errors = '';
            $success = 'Success! Your message has been sent. You should receive a reply within 48 hours.';

            $email = $_POST['email']; 
            $name = $_POST['thename']; 
            $comments = $_POST['comments'];
            $number = $_POST['number']; 

            if(empty($name) || empty($email) || empty($comments)) {
                $errors .= "Error: please input a name, email address and your message.";
            } else {
                   if (!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $email)) {
                $errors .= "Error: Invalid email address";
            } else {
                $errors = '';
            }

            if (!preg_match("/^\(?0( *\d\)?){9,10}$/", $number)) {
                $errors .= "Error: Invalid phone number";
            } else {
                $errors = '';
            }
            }



        ?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM