简体   繁体   中英

My contact form will not validate its input fields. It will submit an email to me while my input fields are blank. Any suggestions?

As stated, my php contact form will send me a blank email message however, it will not validate null input values. Any suggestions? I've tried about everything I know to do.

I'm also wondering if there is a way that I can redirect to a thankyou.html page on submit. I remember the php being something like "header..." to redirect.

 if (isset($_POST["submit"])) {
    $name = $_POST['name'];
    $email = $_POST['email'];
    $from = 'Demo Contact Form'; 
    $to = 'email@example.com'; 
    $subject = 'Message from Contact Demo ';

    $body = "From: $name\n E-Mail: $email";

    // Check if name has been entered
    if (!$_POST['name']) = 0; {
        $errName = 'Please enter your name';
    }

    // Check if email has been entered and is valid
    if (!$_POST['email'] || !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL)) {
        $errEmail = 'Please enter a valid email address';
    }

 // If there are no errors, send the email
 if (!$errName && !$errEmail) {
    if (mail ($to, $subject, $body, $from)) {
    $result='<div class="alert alert-success">Thank You! I will be in touch</div>';
} else {
    $result='<div class="alert alert-danger">Sorry there was an error sending your message. Please try again later</div>';
    }
   }
 }
  ?>

HTML...

 <!--FORM-->
 <form role="form" action="contact.php" method="post" class="form-horizontal align-center">
 <div class="form-group col-centered">
  <label class="control-label col-sm-4 text-align-center">NAME</label>
    <div class="control col-sm-4">
        <input type="text" id="name" name="name" class="form-control">
          <?php echo "<p class='text-danger'>$errName</p>";?> 
    </div>
  </div>

 <div class="form-group col-centered">
  <label class="control-label col-sm-4 text-align-center">EMAIL</label>
    <div class="control col-sm-4">
        <input type="text" id="email" name="name" class="form-control">
          <?php echo "<p class='text-danger'>$errEmail</p>";?> 
    </div>
 </div>

 <div class="form-group">
  <label class="control-label  col-sm-4 text-align-center">PHONE</label>
    <div class="col-sm-4">
        <input type="text" name="phone" class="form-control">
    </div>
  </div>
  <div class="control-group">
    <div class="controls">
        <button type="submit" name="submit" value="submit" class="btnSize btn btn-default btn-lg"><strong>SAVE $150</strong></button>
    </div>
  </div>
 </form>

Thanks for your time.

Here's my take on it:

if (isset($_POST["submit"])) {
    $name = !empty( $_POST['name'] ) ? $_POST['name'] : false;
    $email = !empty( $_POST['email'] ) ? filter_var($_POST['email'],FILTER_VALIDATE_EMAIL) : false;

    if( $name && $email ){

        $from = 'Demo Contact Form';
        $to = 'email@example.com';
        $subject = 'Message from Contact Demo ';

        $body = "From: $name\n E-Mail: $email";

        if (mail ($to, $subject, $body, $from)) {
            $result='<div class="alert alert-success">Thank You! I will be in touch</div>';
        } else {
            $result='<div class="alert alert-danger">Sorry there was an error sending your message. Please try again later</div>';
        }
    }else{
        $errors = [];
        if( !$name ) $errors [] ='Invalid Name entered';

        if( !$email ) $errors [] ='Invalid Email entered';

        $result= '<div class="alert alert-danger">'.implode('<br>', $errors ).'</div>';
    }
}

filter_var() returns the filtered var or false on failure, so with that and the ternary {if} ? true : false; {if} ? true : false; we can normalize your input and simply everything after that.

We check the inputs as soon as possible, that way we run as little code as needed to get to the end result. We know right away if they are good and can skip the majority of the email code, and output our error message.

Logically we can dump the error flag, an in the else we know one or both inputs are false. The array and implode is just a simpler way of putting in a line break. It's also easier to extend by just adding another input in with minimal code changes. As you can see it would be very easy to add another ternary statement, an and condition and an error message. ( only 2.5 ish lines )

One thing I would do on top of that is this

 $post = array_map('trim', $_POST);

And then change all the $_POST to $post , this will account for names added in as spaces or extra white space from Copy and Pasting, a common occurrence.

Further you may be able to minimize the errors like this

}else{
    $result= '<div class="alert alert-danger">'.implode('<br>', array_filter([
        $name ? false : 'Invalid Name entered',
        $email ? false : 'Invalid Email entered',
    ])).'</div>;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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