Jump to content

Contact Us Form With Required Fields


BryanVest

Recommended Posts

Hi I am learning PHP and  working on a Contact Us page with a required fields. For some reason it works great for the name and email, but always says please enter your phone number. If you guys have a better way of doing this please let me know. Also if the email is sent successfully I want it to goto the page "success.html" this part works good though just need some help please :)

 

 

Here is the form:

<form action="contact.php" method="post" id="contactform">
          <ol>
            <li>
              <label for="name">Full Name <span class="red">*</span></label>
              <input id="name" name="name" class="text" />
            </li>
            <li>
              <label for="email">Your email <span class="red">*</span></label>
              <input id="email" name="email" class="text" />
            </li>
            <li>
              <label for="phone">Phone Number <span class="red">*</span></label>
              <input id="phone" name="phone" class="text" />
            </li>
            <li>
              <label for="company">Company</label>
              <input id="company" name="company" class="text" />
            </li>
            <li>
              <label for="topic">Subject<span class="red">*</span></label>
              <input id="topic" name="topic" class="text" />
            </li>
            <li>
              <label for="comments">Message <span class="red">*</span></label>
              <textarea id="comments" name="comments" rows="6" cols="50"></textarea>
            </li>
            <li class="buttons">
              <input type="image" name="imageField" id="imageField" src="images/send.gif" />
            </li>
          </ol>
        </form>

 

 

The PHP code I tried:

 

<?php
// Pick up the form data and assign it to variables
$name = check_input ($_POST['name'], "Please enter your name");
$email = check_input ($_POST['email'],"Please enter your email");
$phone = check_input ($_POST['phone'], "Please enter your phone number");
$company = $_POST['company'];
$topic = check_input ($_POST['topic'], "Please enter your subject");
$comments = check_input ($_POST['comments'], "Please enter your message");


function check_input($data, $problem='')
{
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    if (strlen($data) == 0)
    {
          die($problem);
} else {
  return $data;
}
   
}


// Build the email (replace the address in the $to section with your own)
$to = 'email@email.com"';
$subject = "New message: $topic";
$message = "Email: $email \n Phone: $phone \n Company: $company \n $name said: $comments";
$headers = "From: $email";


// Send the mail using PHPs mail() function
mail($to, $subject, $message, $headers);

// Redirect
header("Location: success.html");
?>

Link to comment
Share on other sites

I want the error to show on the HTML page above the form if they are missing the required field. I have seen this so I know its possible

 

You can only display this on the html page using jQuery (Google it).

 

Although you can just as easily make the html page a .PHP and store the result in a session variable.

Which is then displayed.

Link to comment
Share on other sites

I want the error to show on the HTML page above the form if they are missing the required field. I have seen this so I know its possible

 

Turn your form into a php script.  I'm going to assume you name it form.php.  You'll leave it as is, but inside the body you'll want to add something like this at the top:

 

0)): ?>
</pre>
<ul class="error">

  

</ul>
<b

 

Your current script will become the script that is called both to display and process the form.  The basic pseudo code needs to be:

 

$postdata = array();
if (isset($_POST)  &&  validateform($postdata, $errors)) {
     // send email code using cleaned data in $postdata array
     // redirect to success
     // exit();  -- You always want to exit after a header(location...) to prevent people from trying to exploit your script
}   
require_once('form.php');

 

So hopefully you understand that what will happen is that when the script starts, it will check to see that there is data in the $_POST and then your validateform() function will need to check for errors.  Any errors it finds it will add a message to the array $errors.  You need to declare the $errors array to be passed by reference.  If there is no $_POST data OR the form has post data but fails validation it will fall through and display the form, because it's required at the bottom.  When the form passes validation, you will process, redirect and exit, so that the form is never displayed.  In the process of validation you'll build the array $errors. Any $errors that exist will be picked up in the form code and displayed in a ul at the top.  This is the best practice because you want to alert the user to all the errors you found so that they have all the errors shown to them immediately rather than fixing one only to stumble on the next.  You can also add usability to your form by using the $_POST[] variables to set the values of the form elements.  That way if they make mistakes, their prior entries will already be filled in, so they don't have to rekey all the data into the form.

 

function validateform(&$postdata, &$errors) {
  // move in your code here that calls your check_input() function.  Return your sanitized data to the $postdata array that you pass by reference to it. 
  // example:
  $postdata['email'] = check_input('email', 'Please enter your name', $errors);
'  // add the others
  return (count($errors) > 0);
}

 

Notice that I don't pass in $_POST because it is a superglobal and doesn't need to be passed to a function.  It's already global.  You can just pass the key name.

 

function check_input($key, $problem='', &$errors)
{
    $data = trim($_POST[$key]);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    if (strlen($data) == 0)
    {
          $errors[] = $problem;
     }
     return $data;
}

 

This is roughly what I might do given your existing code.  It's not really the best structure, because check_input really doesn't allow for you to implement any customized validation rules, but once you get the basic skeleton together and see how to implement this you can always improve on it.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.