简体   繁体   中英

Validating all the fields to display the error message in Contact Form in PHP

I need to include more then one error if i click on Submit button. if a user didn't filled all the required fields..error should be shown on top of my form Currently when i Hit the submit button, The errors was pointing to the "Comment" line and Only the "Comment" errors was shown

I used - $error=$error."<br/> or $error.="<br /> none of them working as expected

How to display all my fields with and error message? My Code has shown below

<?php
if ($_POST["submit"]) {
    if($_POST['email']) {
        $error="<br/>Please enter your Email address";
    }

    if($_POST['dest']) {
        $error.="<br/>Please enter your Destination Name ";
    }

    if($_POST['dcity']) {
        $error.="<br/>Please enter your Departure City ";
    }

    if($_POST['name']) {
        $error.="<br/>Please enter your Name ";
    }

    if($_POST['cnum']) {
        $error.="<br/>Please enter your Contact Number";
    }

    if($_POST['adults']) {
        $error.="<br/>Please enter Number Of Adults";
    }

    if($_POST['child']) {
        $error.="<br/>Please enter Number Of Children";
    }

    if($_POST['comment']) {
        $error.="<br/>Please enter Your Comments ";
    }

    if ($error){
        $result='<div class="alert alert-danger"><strong>There were error(s) in your form:</strong>' .$error.' </div>'; 
    }
}
?>

First of all, you should check properly if the fields are empty, like so:

if(empty($_POST['email'])) {

Your code is actually doing the opposite, currently the condition is matched if the variable is true(-ish). In any case, to save yourself from warnings, use empty() or !empty() -- in case of POST data; otherwise also isset() etc. -- rather than directly testing a variable that may or may not exist.

Second, you should either: Use an array for pooling up your errors: $error = []; ... $error[] = 'This error'; $error = []; ... $error[] = 'This error'; -- Or: first define an empty string, $error = ''; before trying to concatenate with .= to it. As it stands, your code only defines the error variable if the email field is unset. Using an array will spare you from the <br /> concatenation hassle as well; just implode('<br />', $error) .


Edit: If you want to get rid of all that repetitive checking and redundant code, and make it easier to extend your app in the future, you could abstract things a bit and do something like this:

$err_msgs = [
    'email' => 'your Email address',
    'dest' => 'your Destination Name',
    'dcity' => 'your Departure City',
    'name' => 'your Name',
    'cnum' => 'your Contact Number',
    'adults' => 'Number Of Adults',
    'child' => 'Number Of Children',
    'comment' => 'your Comments',
];

$errors = [];

foreach($err_msgs as $key => $msg) {
    if (empty($_POST[$key])) {
        $errors[] = 'Please enter ' . $msg;
    }
}

if (count($errors) > 0) { // OR: if (!empty($errors)) {
    $result = '<div class="alert alert-danger"><strong>
              There were error(s) in your form:</strong><br />'
              . implode('<br />', $errors) 
              . ' </div>';
}

What's happening here: We define all expected fields and their unique error messages in an array as key/message pairs, the keys being identical to your form fields' names. Then we loop over the array and check for empty fields, and generate all error messages in one place, adding them into an array. Finally, if the $errors array has messages, we print them out.

Best solution: Assign an empty string: $error = ''; then you will concatenate it. Ie

if($_POST['some_key']){
   $error .= 'this is an error';
}
//...
if($error != '') {
   echo $error;
}

I think the issues you met due to a case:

if email exist so what $error to concatenate after that.

But as usual, we validate those like this:

if(isset($_POST['some_key']) && empty(trim($_POST['some_key']) {
    //put error string here
}

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