Php Contact Form - Optional Fields (trim)

我们两清 提交于 2019-12-13 06:19:28

问题


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



来源:https://stackoverflow.com/questions/11770372/php-contact-form-optional-fields-trim

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!