user3786102 user3786102 - 1 year ago 55
HTML Question

Change a field in PHP form from required to optional

I am a complete novice when it comes to PHP. I downloaded a form I found online to include in my Bootstrap site. It is a very simple form anyone can use to send me a message. I managed to set up Wamp to test out the PHP but when I leave the Phone field blank it gives me an error message telling me please go back and correct the error. I want to make it so if someone leaves out the phone number it still sends the email. Thank you.


<form name="contactform" method="post" action="index.php" class="form-vertical">
<div class="form-group">
<label for="inputName" class="control-label">Name</label>
<input type="text" class="form-control" id="inputName" name="inputName" placeholder="First and Last">
<div class="form-group">
<label for="inputEmail" class="control-label">Email*</label>
<input type="text" class="form-control" id="inputEmail" name="inputEmail" placeholder="Required">
<div class="form-group">
<label for="inputPhone" class="control-label">Phone Number</label>
<input type="text" class="form-control" id="inputPhone" name="inputPhone" placeholder="Optional">
<div class="form-group">
<label for="inputMessage" class="control-label">Message</label>
<textarea class="form-control" rows="5" id="inputMessage" name="inputMessage" placeholder="Brief Description"></textarea>
<div class="form-group">
<button type="submit" class="btn btn-custom pull-right hvr-underline-from-left">Send</button>


/* Set e-mail recipient */
$myemail = "";

/* Check all form inputs using check_input function */
$name = check_input($_POST['inputName'], "First and Last");
$email = check_input($_POST['inputEmail'], "Required");
$phone = check_input($_POST['inputPhone'], "Optional");
$message = check_input($_POST['inputMessage'], "Brief Description");

/* If e-mail is not valid show error message */
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $email)) {
show_error("Invalid e-mail address");
/* Let's prepare the message for the e-mail */

$subject = "Contact Message from";

$message = "

Someone has sent you a message using your contact form:

Name: $name
Email: $email
Phone: $phone



/* Send the message using mail() function */
mail($myemail, $subject, $message);

/* Redirect visitor to the thank you page */

/* Functions we used */
function check_input($data, $problem='')
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
if ($problem && strlen($data) == 0)
return $data;

function show_error($myError)

<p>Please correct the following error:</p>
<strong><?php echo $myError; ?></strong>
<p>Hit the back button and try again</p>


Answer Source

Please change this line:

$phone = check_input($_POST['inputPhone'], "Optional");


$phone =  check_input($_POST['inputPhone']);

This way show_error($problem); won't be called.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download