1

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.

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.

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']};
";
                // [email protected]
                $to = 'test-email-deleted-for-stackoverflow'; 
                $subject = 'Message from Portfolio';
                $from = $_POST['thename'];
                // [email protected]
                $fromEmail = 'test-email-deleted-for-stackoverflow';
                $header = 'From: ' . $from . '<' . $fromEmail . '>';
                mail($to,$subject,$message,$header);
            ?>
        <?php endif; ?>
    <?php endif; ?>
5
  • 1
    You need to provide the code that contains the conditions for sending the email or not. Commented Jan 15, 2017 at 14:02
  • Thanks @JBES, provided above. Commented Jan 15, 2017 at 14:04
  • I think you have to delete your else-clauses, because every correct check will delete all previour setted errors. Commented Jan 15, 2017 at 14:06
  • so just break up your ` if(empty($name) || empty($email) || empty($comments)) { $errors .= "Error: please input a name, email address and your message."; } else { $errors = ''; }` block into individual error messages and get rid of the else statements Commented Jan 15, 2017 at 14:06
  • otherwise you can use $errors as an array and have multiple errors listed. , e.g.$errors[]= "Invalid email address" ... Then you just need to check if count($errors) >0 to know if the form is invalid Commented Jan 15, 2017 at 14:08

3 Answers 3

1

Your problem is that you are resetting $errors back to '' each time one of your validation conditions passes:

        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. 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)) {
Sign up to request clarification or add additional context in comments.

1 Comment

Wonderful! Thankyou for such a helpful explanation too :)
1

Based on the information Supplied, i think you should use a complex if-elseif-else statement like so:

`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
                }

2 Comments

Thankyou, very helpful :)
Alex i am glad to help.I have been helped a lot on this platform.Glad to return the favor.
1

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 = '';
            }
            }



        ?>

3 Comments

it checks the valid email and phone only when your email,comments,name are not empty.
in your code if your message is empty at that time $error get message but your email address is proper so that it further becomes blank and message sent
if you need any help then you can ask

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.