Php Contact Form - Optional Fields (trim)

2019-09-15 01:40发布

问题:

I have a php contact form I'm trying to edit to suit my needs. Currently, every field needs to be filled out in order for the form to work. What do I need to edit in order to make some fields optional? Below isn't the full script, but I have a feeling its the segment of the field most important for what I need to do.

Thanks

$name    = $_POST['name'];
$email  = $_POST['email'];
$phone  = $_POST['phone'];
$date    = $_POST['date'];
$guests  = $_POST['guests'];
$subject  = $_POST['subject'];
$comments = $_POST['comments'];

if (isset($_POST['verify'])) : 
    $posted_verify   = $_POST['verify']; 
    $posted_verify   = md5($posted_verify); 
else :
    $posted_verify = '';
endif;

// Important Variables
$session_verify = $_SESSION['verify'];

if (empty($session_verify)) $session_verify = $_COOKIE['verify'];

$error = '';

    if(trim($name) == '') {
        $error .= '<li>Your name is required.</li>';
    }

    if(trim($date) == '') {
        $error .= '<li>Your event date is required.</li>';
    }

    if(trim($email) == '') {
        $error .= '<li>Your e-mail address is required.</li>';
    } elseif(!isEmail($email)) {
        $error .= '<li>You have entered an invalid e-mail address.</li>';
    }

    if(trim($phone) == '') {
        $error .= '<li>Your phone number is required.</li>';
    } elseif(!is_numeric($phone)) {
        $error .= '<li>Your phone number can only contain digits.</li>';
    }


    if(trim($comments) == '') {
        $error .= '<li>You must enter a message to send.</li>';
    }

    if(trim($guests) == '') {
        $error .= '<li>The number of guests is required.</li>';
    } elseif(!is_numeric($guests)) {
        $error .= '<li>Your phone number can only contain digits.</li>';
    }

回答1:

remove the if statement for the variables you would like to be optional.

example remove this for name to be optional: if(trim($name) == '') { $error .= '<li>Your name is required.</li>'; }