Jump to content

[SOLVED] can't stop validation errors from displaying on form page load instead of submit


simcoweb

Recommended Posts

Ok, creating two forms and they work fine. Problem is that the validation errors display immediately on page load instead of on submit. Here's the full code for the form parsing:

 

<?php
// form parser and database insertion
include "db_config.inc";

// Turn on magic quotes to prevent SQL injection attacks
if(!get_magic_quotes_gpc())
set_magic_quotes_runtime(1);
//if(isset($_POST['submit'])){
// post the results in variables to work with
$fname = strip_tags(trim($_POST['first_name']));
$lname = strip_tags(trim($_POST['last_name']));
$email = strip_tags(trim($_POST['email']));
$dayphone = strip_tags(trim($_POST['day_phone']));
$altphone = strip_tags(trim($_POST['alt_phone']));
$besttime = strip_tags(trim($_POST['best_time']));
$address = strip_tags(trim($_POST['address']));
$city = strip_tags(trim($_POST['city']));
$state = strip_tags(trim($_POST['state']));
$zip = strip_tags(trim($_POST['zip']));
$mortgage = strip_tags(trim($_POST['type_mortgage']));
$first_mtg = strip_tags(trim($_POST['first_company']));
$months_behind = strip_tags(trim($_POST['months_behind']));
$back_payments = strip_tags(trim($_POST['back_payments']));
$notice = strip_tags(trim($_POST['notice_of_foreclosure']));
$auction = strip_tags(trim($_POST['auction_date']));
$auction_date = strip_tags(trim($_POST['date_of_auction']));
$second_mortgage = strip_tags(trim($_POST['second_company']));
$balances = strip_tags(trim($_POST['combined_balances']));
$payments = strip_tags(trim($_POST['combined_payments']));
$bankruptcy = $_POST['in_bankruptcy'];
$situation = strip_tags(trim($_POST['situation']));
$keep_sell = $_POST['keep_property'];
$referred = $_POST['referred_by'];
$today = date("F j, Y, g:i a");

// set error message variable for later use
$err_message = array();

// validate the form input
if (empty($_POST['first_name']) || empty($_POST['last_name']) || empty($_POST['email']) || 
   empty($_POST['day_phone'])) {
     $err_message[] = "<font face='Verdana' size='2' color='#FF0000'>Your first name, last name, email address
        and daytime phone number are required. Please complete those fields and resubmit.</font>";
}
// validate email address format
if ($email) {
        if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)) {
            $err_message[] = $email. " is not a valid email address. Please enter a valid email address.<br/>";
        }
    }
if (empty($_POST['address']) || empty($_POST['city']) || empty($_POST['state']) || empty($_POST['zip'])) {
  $err_message[] ="<font face='Verdana' size='2' color='#FF0000'>Please complete ALL fields in the property information section and resubmit";
}
//}
if (!$err_message) {
$link = mysql_connect($dbhost, $dbuser, $dbpass) or die(mysql_error());
  mysql_select_db($dbname, $link) or die(mysql_error());
  // run our query to insert the record
  $sql = "INSERT INTO leads (first_name, last_name, email, day_phone, alt_phone, best_time, address, 
  			city, state, zip, type_mortgage, first_company, months_behind, back_payments, notice_of_foreclosure,
	  auction_date, date_of_auction, second_company, combined_balances, combined_payments, in_bankruptcy,
	  situation, keep_property, referred_by, date ) 
	  VALUES ('$fname', '$lname', '$email', '$dayphone', '$altphone', '$besttime', '$address', '$city', 
	  '$state', '$zip', '$mortgage', '$first_mtg', '$months_behind', '$back_payments', '$notice', '$auction', 
	  '$auction_date', '$second_mortgage', '$balances', '$payments', '$bankruptcy', '$situation', '$keep_sell',
	  '$referred', '$today')";
  $results = mysql_query($sql, $link) or die(mysql_error());
  $new_id = mysql_insert_id();
  
    // start mail process
$mailContent="--------CONTACT--------\n"
            ."Name: ".$fname." ".$lname."\n"
            ."Date: ".$today."\n"
            ."E-mail: ".$email."\n\n--------PHONE--------\n"
            ."Phone: ".$day_phone."\n"
            ."Alt Phone: ".$alt_phone."\n"
            ."Best time to call: ".$best_time."\n\n--------Details--------\n"
            ."Address: ".$address."\n"
		."City: ".$city."\n"
		."State: ".$state."\n"
		."Zip: ".$zip."\n\n---------Foreclosure Info---------\n"
		."Loan type: ".$mortgage."\n"
		."First Mtg: ".$first_mtg."\n"
		."Months behind: ".$months_behind."\n"
		."Back payments: ".$back_payments."\n"
		."Notice of foreclosure filed: ".$notice."\n"
		."Auction date set: ".$auction."\n"
		."Date of auction: ".$auction_date."\n"
		."Second mortgage: ".$second_mortgage."\n"
		."Combined balances: ".$balances."\n"
		."Combined payments: ".$payments."\n"
		."Are you in bankruptcy: ".$bankruptcy."\n"
		."Situation detail: ".$situation."\n"
		."Keep or Sell: ".$keep_sell."\n\n----------Other---------\n"
		."Referred by: ".$referred."\n";
//----------------------------------
$toAddress="bsniff@gmail.com"; /* change this! */
$subject="WA HomeSaver Inquiry"; /* change this! */
$recipientSubject="WA HomeSaver Inquiry"; /* change this! */
$receiptMessage = "Thank you ".$fname." for inquiring at WAHomeSaver.com's website!\n\n\nHere is the contact information you submitted to us:\n\n"
            ."--------CONTACT--------\n"
            ."Name: ".$fname." ".$lname."\n"
            ."E-mail: ".$email."\n\n--------PHONE--------\n"
            ."Phone: ".$day_phone."\n"
            ."Alternate phone: ".$alt_phone."\n"
            ."Best time to contact? ".$best_time."\n";
//----------------------------------
mail($email, $subject, $receiptMessage,"From:$toAddress");
//----------------------------------
mail($toAddress,$recipientSubject,$mailContent,"From:$email");

  if($results) {
    header("Location: success.php?id=$new_id");
    exit;
} else {
  header("Location: error.php");
}
}
?>

 

Now, notice the lines i've commented out:

 

if(isset($_POST['submit'])) {

 

}

 

 

If I uncomment this I get a 500 error. But, to me, this bit of code is telling the validation to occur IF the form was submitted.

 

How can I stop the page from displaying the error messages until after submit?

 

If you want to see: http://www.wahomesaver.com/response.php

Link to comment
Share on other sites

Try...

 

if (isset($_POST['I1'])) {

 

You don't have any form element called submit.

 

You should wrap all these other lines in a conditional aswel, or if any are left blank they will generate Notices.

 

$fname = ($_POST['first_name'] ? strip_tags(trim($_POST['first_name'])) : '');

Link to comment
Share on other sites

thorpe, I need some further guidance here. Or, from anyone .. :)

 

Ok, I added the if(isset($_POST['submit'])) {  line ( and did, by the way, change the T1 name to 'submit'  so now I DO have a submit field name ) and placed it around the errors and code that follows like so:

 

<?php
if(isset($_POST['submit'])) {

// set error message variable for later use
$err_message = array();

// validate the form input
if (empty($_POST['first_name']) || empty($_POST['last_name']) || empty($_POST['email']) || 
   empty($_POST['day_phone'])) {
     $err_message[] = "Your first name, last name, email address
        and daytime phone number are required. Please complete those fields and resubmit.";
}
// validate email address format
if ($email) {
        if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)) {
            $err_message[] = $email. " is not a valid email address. Please enter a valid email address.";
        }
    }
if (empty($_POST['address']) || empty($_POST['city']) || empty($_POST['state']) || empty($_POST['zip'])) {
  $err_message[] ="Please complete ALL fields in the property information section and resubmit";
}

if (!$err_message) {
$link = mysql_connect($dbhost, $dbuser, $dbpass) or die(mysql_error());
  mysql_select_db($dbname, $link) or die(mysql_error());
  // run our query to insert the record
  $sql = "INSERT INTO leads (first_name, last_name, email, day_phone, alt_phone, best_time, address, 
  			city, state, zip, type_mortgage, first_company, months_behind, back_payments, notice_of_foreclosure,
	  auction_date, date_of_auction, second_company, combined_balances, combined_payments, in_bankruptcy,
	  situation, keep_property, referred_by, date ) 
	  VALUES ('$fname', '$lname', '$email', '$dayphone', '$altphone', '$besttime', '$address', '$city', 
	  '$state', '$zip', '$mortgage', '$first_mtg', '$months_behind', '$back_payments', '$notice', '$auction', 
	  '$auction_date', '$second_mortgage', '$balances', '$payments', '$bankruptcy', '$situation', '$keep_sell',
	  '$referred', '$today')";
  $results = mysql_query($sql, $link) or die(mysql_error());
  $new_id = mysql_insert_id();
  
    // start mail process
$mailContent="--------CONTACT--------\n"
            ."Name: ".$fname." ".$lname."\n"
            ."Date: ".$today."\n"
            ."E-mail: ".$email."\n\n--------PHONE--------\n"
            ."Phone: ".$dayphone."\n"
            ."Alt Phone: ".$altphone."\n"
            ."Best time to call: ".$besttime."\n\n--------Details--------\n"
            ."Address: ".$address."\n"
		."City: ".$city."\n"
		."State: ".$state."\n"
		."Zip: ".$zip."\n\n---------Foreclosure Info---------\n"
		."Loan type: ".$mortgage."\n"
		."First Mtg: ".$first_mtg."\n"
		."Months behind: ".$months_behind."\n"
		."Back payments: ".$back_payments."\n"
		."Notice of foreclosure filed: ".$notice."\n"
		."Auction date set: ".$auction."\n"
		."Date of auction: ".$auction_date."\n"
		."Second mortgage: ".$second_mortgage."\n"
		."Combined balances: ".$balances."\n"
		."Combined payments: ".$payments."\n"
		."Are you in bankruptcy: ".$bankruptcy."\n"
		."Situation detail: ".$situation."\n"
		."Keep or Sell: ".$keep_sell."\n\n----------Other---------\n"
		."Referred by: ".$referred."\n";
//----------------------------------
$toAddress="bsniff@gmail.com"; /* change this! */
$subject="WA HomeSaver Inquiry"; /* change this! */
$recipientSubject="WA HomeSaver Inquiry"; /* change this! */
$receiptMessage = "Thank you ".$fname." for inquiring at WAHomeSaver.com's website!\n\n\nHere is the contact information you submitted to us:\n\n"
            ."--------CONTACT--------\n"
            ."Name: ".$fname." ".$lname."\n"
            ."E-mail: ".$email."\n\n--------PHONE--------\n"
            ."Phone: ".$day_phone."\n"
            ."Alternate phone: ".$alt_phone."\n"
            ."Best time to contact? ".$best_time."\n";
//----------------------------------
mail($email, $subject, $receiptMessage,"From:$toAddress");
//----------------------------------
mail($toAddress,$recipientSubject,$mailContent,"From:$email");

  if($results) {
    header("Location: success.php?id=$new_id");
    exit;
} else {
  header("Location: error.php");
}
}
}
?>

 

Now, when I do this NO error message show up on page load. BUT, if I try to force errors by simply hitting submit without filling in any of the required fields the page just refreshes and no errors show up.

 

So, I think i'm close here but what I need is for:

 

1. validation errors only show IF the form has been submitted

2. correct field entries to remain IF the form has been submitted

 

Help...anyone? :)

Link to comment
Share on other sites

You are making it complicated.

 

Just use something like this you will need to adapt it to match yours.

 

<?php

if ($_POST['submit'])
{

// get the posts and check errors

if (!$_POST['field'] || !$_POST['field1'])
echo "The fields are empty";
}else{
// do the code
}
}
?> 

Link to comment
Share on other sites

first, this line:

if (!$err_message) {

will always be false since you've already established the variable as an array at the top, so you can't be inserting data every time you submit your form.

 

second, if there IS an error, you're sending the user to another page... how is the data in the error array supposed to get to the next page?

Link to comment
Share on other sites

boo_lolly, I interpreted that line:

 

if(!$err_message)

 

to mean that if that variable/array is empty then proceed with the following. Isn't that the same as saying:

 

if(empty($err_message)) {

do this

}

 

?

 

If there's no errors in validation then the query and mailing should take place. I'm trying to resolve that problem since the code gets run regardless.

 

Hughesy, that's pretty much what I have except for the 'else' statement. However, in your example it echoes the error message whereas i'm stuffing them into an array to be displayed in the page in a bullet list.

 

So, I think what I need is the 'if' statement for the validation and the 'else' statement for running the code IF there's no errors

 

Ideas? Thoughts? Am I off track? :)

 

Link to comment
Share on other sites

Actually error.php doesn't contain any of the errors from the array. That's an error page that is produced only if the query code doesn't work. So, it's insignificant. The validation errors are all displayed in the main body of the web page above the form itself in red and in a bulleted list using this code:

 

 <?php
if(!empty($err_message)) {
echo "<strong id='errorTitle'>One or more input fields on the form has not been completed</strong>";
echo "<ul>";
foreach ($err_message as $value) {
echo "<li>$value</li>";
} 
echo "</ul>";
}
?>

 

So, once again, the error.php isn't involved in the matter. My problem is validating the form input, displaying the errors, not allowing the other code to run (query, mail, etc.) until all fields being validated are completed properly.

Link to comment
Share on other sites

sorry for the misunderstanding, try this:

<?php
if(array_key_exists(0, $err_message)) {
echo "<strong id='errorTitle'>One or more input fields on the form has not been completed</strong>";
echo "<ul>";
foreach ($err_message as $value) {
echo "<li>$value</li>";
} 
echo "</ul>";
}
?>

Link to comment
Share on other sites

Sorry, boo.. but I think we're off track here. The error messages are displaying fine using the code that I just posted. That's not the problem. The problem, in sequence, is this:

 

1. when I first go to the page http://www.wahomesaver.com/response.php it displays all the error messages as if the form has been submitted, which, of course, it hasn't yet since you just got there. It also executes the mail() function part of the code as well as the query. So, I get blank email and a blank entry into the database

 

2. say I fill out the form but leave a required field blank. When the page refreshes it will display the field error only, not all the validation errors like when you first arrived there. Plus it emails again AND enters into the database again.

 

3. What I need to do is tweak the code so that it doesn't automatically submit the form/data/mail on arrival (like, waits for a submit confirmation if(isset($_POST['submit']))  for example).

 

So, the form needs to:

 

display on arrival

display errors AFTER submissions IF there are errors

if no errors, parse the query and the mail

 

Just an FYI, and I don't know WHY this happens, but if I place that if(isset tag in the code it will produce a 500 server error. It depends, though, on where I put the closing }. If I place it in front of the closing ?> tag with the opening if(isset blah blah { ahead of the error checking then it doesn't crash. But, that doesn't stop the code for the mail() and query to run. So, if I put it right after the last error check then it crashes. I even tried rewriting using an 'else' statement instead of the if($err_message=="") { and that caused a 500 error. Not sure what that's all about.

 

So, in summary, I need help tweaking this code to do what i've outlined above. Thanks in advance! :)

 

 

Link to comment
Share on other sites

I just saw this thread ...

 

Here's how I usually do my form validations:

<?php
$err_message = array();
$clean_data = array();
$qtmp = array();
if (isset($_POST['submit'])) {
   foreach ($_POST as $fld => $val) {
       switch($fld) {
            case 'first_name':
            case 'last_name':
            case 'email':
            case 'day_phone':
                 if (strlen(trim(stripslashes($val))) == 0)
                       err_message[] = 'Your first name, last name, email address and daytime phone number are required. Please complete those fields and resubmit.';
                 else {
                       $clean_data[$fld] = trim(stripslashes($val));
                       $qtmp[] = $fld . " = '" . mysql_real_escape_string($clean_data[$fld]) . "'";
                 }
                 break;
            case 'address':
            case 'city':
            case 'state':
            case 'zip':
                 if (strlen(trim(stripslashes($val))) == 0)
                       err_message[] = 'Please complete ALL fields in the property information section and resubmit';
                 else {
                       $clean_data[$fld] = trim(stripslashes($val));
                       $qtmp[] = $fld . " = '" . mysql_real_escape_string($clean_data[$fld]) . "'";
                 }
                 break;
            case 'email':
                 if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email))                        
                       $err_message[] = $email. ' is not a valid email address. Please enter a valid email address.';
                 else {
                       $clean_data[$fld] = trim(stripslashes($val));
                       $qtmp[] = $fld . " = '" . mysql_real_escape_string($clean_data[$fld]) . "'";
                 }
                 break;
            case 'submit':
                 break;
            default:
                 clean_data[$fld] = trim(stripslashes($val));
                 $qtmp[] = $fld . " = '" . mysql_real_escape_string($clean_data[$fld]) . "'";
       }
   }
}
if (!empty($err_messge)) {
      echo '<span style="color:red">' . implode("<br>\n",$err_message) . "<br>\n":
else {
      $link = mysql_connect($dbhost, $dbuser, $dbpass) or die(mysql_error());
      mysql_select_db($dbname, $link) or die(mysql_error());
  // run our query to insert the record
      $sql = "INSERT INTO leads set " . implode(', ',$qtmp); // this uses the alternative format of the MySQL insert command
      $results = mysql_query($sql, $link) or die(mysql_error());
      $new_id = mysql_insert_id();
  
    // start mail process
//
// Change the next lines to use the values out of the $clean_data array instead of the standalone variable names.
//
}
?>

 

Ken

Link to comment
Share on other sites

kenrbnsn, you rock this place :) 

 

Ok, i'll adapt what you've posted and report back. Also, i'll save this as a 'snippet' to utilize in the future. Hopefully I won't screw it up and be back here in 15 mins. posting bugs ;)

 

 

If you could do me a favor, provide me with a quick example of the right syntax for the clean_data array field names?

Link to comment
Share on other sites

Where you have:

<?php
            ."Name: ".$fname." ".$lname."\n"
?>

change it to

<?php
            ."Name: ".$clean_data['first_name']." ".$clean_data['last_name']."\n"
?>

You just have to make sure you use the field names from your form, not the made up variable names.

 

You want to use the variable "$today" as is, since that didn't come from the form.

 

Ken

 

Link to comment
Share on other sites

Cool, that's what i've been inserting while I was awaiting your response. A good guess :)

 

On the $today, yes...I counted on using that as is since it's a separate variable not created by the form. I'll set that value above your code.

 

I'll report back, and thanks again!

Link to comment
Share on other sites

I'm getting this:

 

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1

 

There were numerous other miscellaneous syntax errors I had to clean up as well... some missing $'s and a couple of other tweaks. But after all those, this is the one that's left and i'm not familiar with that method you're using for the INSERT. Ideas?

Link to comment
Share on other sites

Change the mysql_query statement to:

<?php
$results = mysql_query($sql) or die("Problem with the query: <pre>$sql</pre><br>" . mysql_error());
?>

 

This will show the contents of the query. Post this and we can determine what went wrong.

 

The alternative format that I use is just like the format for a mysql "update" query. I find it easier to use and you never have to worry about mismatched number of fields and values.

 

Ken

Link to comment
Share on other sites

It looks like nothing got inserted into the $qtmp array.

 

Change:

<?php
      $sql = "INSERT INTO leads set " . implode(', ',$qtmp); // this uses the alternative format of the MySQL insert command
?>

to

<?php
      echo '<pre>' . print_r($qtmp,true) . '</pre>';
      $sql = "INSERT INTO leads set " . implode(', ',$qtmp); // this uses the alternative format of the MySQL insert command
?>

 

This will show what's in the $qtmp array.

 

Ken

Link to comment
Share on other sites

Good call. The array is empty:

 

Array

(

)

 

Problem with the query

 

INSERT INTO leads set

 

 

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1

Link to comment
Share on other sites

<?
if (isset($_POST['submit'])) {
   foreach ($_POST as $fld => $val) {
       switch($fld) {
            case 'first_name':
            case 'last_name':
            case 'email':
            case 'day_phone':
                 if (strlen(trim(stripslashes($val))) == 0)
                       $err_message[] = 'Your first name, last name, email address and daytime phone number are required. Please complete those fields and resubmit.';
                 else {
                       $clean_data[$fld] = trim(stripslashes($val));
                       $qtmp[] = $fld . " = '" . mysql_real_escape_string($clean_data[$fld]) . "'";
                 }
                 break;
            case 'address':
            case 'city':
            case 'state':
            case 'zip':
                 if (strlen(trim(stripslashes($val))) == 0)
                       $err_message[] = 'Please complete ALL fields in the property information section and resubmit';
                 else {
                       $clean_data[$fld] = trim(stripslashes($val));
                       $qtmp[] = $fld . " = '" . mysql_real_escape_string($clean_data[$fld]) . "'";
                 }
                 break;
            case 'email':
                 if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email))                        
                       $err_message[] = $email. ' is not a valid email address. Please enter a valid email address.';
                 else {
                       $clean_data[$fld] = trim(stripslashes($val));
                       $qtmp[] = $fld . " = '" . mysql_real_escape_string($clean_data[$fld]) . "'";
                 }
                 break;
            case 'submit':
                 break;
            default:
                 $clean_data[$fld] = trim(stripslashes($val));
                 $qtmp[] = $fld . " = '" . mysql_real_escape_string($clean_data[$fld]) . "'";
       }
   }
}
?>

Link to comment
Share on other sites

That looks ok.

 

At the top of the script put

<?php
echo '<pre>' . print_r($_POST,true) . '</pre>';
?>

This will show what's being passed to the script.

 

It's past my bedtime (1:10 AM here), so if you don't see a response I'll see it when I wake up...

 

Ken

Link to comment
Share on other sites

Alas, pretty much the same thing :( 

 

Array

(

)

 

Array

(

)

 

Problem with the query

 

INSERT INTO leads set

 

 

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1

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.