Page 1 of 1

Making Form Field Mandatory

Posted: Thu Jan 06, 2011 6:10 pm
by WestCoast?'s
I've been trying to make my contact form engine mandatory for the name, phone number and email fields, but when I upload it on the ftp and test it, I keep getting errors. Here's the code I have that is working without the fields being mandatory:

Code: Select all

<?php

$EmailFrom = "example@gmail.com";
$EmailTo = "example@gmail.com";
$EmailTo = "example@gmail.com";
$EmailTo = "example@gmail.com";
$Subject = "New Lead!!!";
$Name = Trim(stripslashes($_POST['Name'])); 
$Phone_Number = Trim(stripslashes($_POST['Phone_Number'])); 
$Email = Trim(stripslashes($_POST['Email'])); 
$Message = Trim(stripslashes($_POST['Message'])); 

// validation
$validationOK=true;
if (!$validationOK) {
  print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
  exit;
}

// prepare email body text
$Body = "";
$Body .= "Name: ";
$Body .= $Name;
$Body .= "\n";
$Body .= "Phone Number: ";
$Body .= $Phone_Number;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $Email;
$Body .= "\n";
$Body .= "Message: ";
$Body .= $Message;
$Body .= "\n";

// send email 
$success = mail($EmailTo, $Subject, $Body, "From: <$EmailFrom>");

// redirect to success page 
if ($success) {//&& ($Phone_Number != "" || $Email != "") {
  print "<meta http-equiv=\"refresh\" content=\"0;URL=contactthanks.php\">";
}
else{
  print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
}
?>
I would like it to return something that says: "Enter Your Name/Phone Number/Email" corresponding to the appropriate field they didn't fill out. Thanks for any input you can provide!

Re: Making Form Field Mandatory

Posted: Thu Jan 06, 2011 7:12 pm
by anantha
i could not see the form and also i could not see where you are doing validation.

Re: Making Form Field Mandatory

Posted: Fri Jan 07, 2011 12:58 am
by social_experiment
It's easiest to check if a field has a value inside it

Code: Select all

<?php if ($_POST['name'] == '') { echo 'Empty field'; } ?>
To see if your form has been submitted by clicking the submit button

Code: Select all

<?php if (isset($_POST['buttonName'])) ?>

Re: Making Form Field Mandatory

Posted: Fri Jan 07, 2011 5:20 am
by spedula
This would be much easier and better to pull off using javascript, this way you won't waste any page reloads. It's easily done with jQuery.

Example:

Code: Select all

$("#formID").submit( function() {
   if ($("#formFieldID).val() == '') {
      return false;   
   }
});
Or something very close to that. You can reverse the logic and use != in the if statement then execute some other code there and then an else statement returns false.