Reflex84
Reflex84

Reputation: 313

Validating php form - How to show error message on the form

I've been receiving blank submissions from my form and I know that validating ("required" validation) using javascript isn't always effective because spambots can turn off javascript. So I've been looking for ways to validate my php form using php.

So after a but of research ... I found that this will work:

    if (!$_POST['name'] )
{
die('Please fill in your name');
}

Though, this message 'Please fill in your name' shows on a different page after I've hit the submit button. Now ideally, I'd like that message to display on the page where the form is, though I'm struggling to find a way to do this. (Please excuse my lack on knowledge on php).

Would I require Ajax? I assume I would need to add a div on the form page where I want the error message to display? How would I ask php to display the error message on the form page? IE: What would I need to put in my php process form (along with the code above?).

If you need me to post / add any more detail, please ask, as I'd appreciate your help!

====================================================================== UPDATE

Here is my php process form:

<?
session_start();
include("verification_image.class.php");
$image = new verification_image();
if (($image->validate_code($_POST['validate']) ? "true" : "false") == "false") {
    header('Location: http://www.domain.com/fail.htm'); 
    exit;
}

if (!$_POST['rgerger'] )
{
die('You did not complete all of the required fields');
}


if(!empty($_POST['email'])){ die('Stop Spamming'); }

$to = "[email protected]";
$from = $_POST['ervberster']; 
$subject = "I Want to Advertise"; 
$sBodyNew = '<style type="text/css">
<!--
.style {
font-family: Arial;
font-size: 12px;
color: #4D241E;
}
body {
background-image: url();
background-color: #F1EAE4;
}
.style1 {font-size: 14px}
-->
</style>
<p>&nbsp;</p>
<table width="420" border="0" align="center" cellpadding="0" cellspacing="5">
 <tr>
<td><table width="100%"  border="0" cellpadding="8" cellspacing="0" bgcolor="#E7D3AF" 
class="style">
  <tr>
    <td colspan="2" valign="top"><div align="center"><strong><span class="style1">I 
Want to Advertise on AccommodationMozambique.co.za</span><br>
 &nbsp;.................................................</strong><br>
 &nbsp;</div></td>
    </tr>
  <tr>
    <td width="32%" valign="top"><div align="left"><strong>Date Submitted</strong>
 </div></td>
    <td width="68%" valign="top">'. date("F j, Y, g:i a") .'</td>
  </tr>
  <tr>
    <td valign="top"><div align="left"><strong>Name</strong></div></td>
    <td valign="top">'.$_POST['name'].'</td>
  </tr>
        <tr>
    <td valign="top"><div align="left"><strong>Email</strong></div></td>
    <td valign="top">'.$_POST['ervberster'].'</td>
  </tr>
  <tr>
    <td valign="top"><div align="left"><strong>Telephone</strong></div></td>
    <td valign="top">'.$_POST['werergrggef'].'</td>
  </tr>
  <tr>
    <td valign="top"><div align="left"><strong>Name of Lodge</strong></div></td>
    <td valign="top">'.$_POST['hneyjyttyh'].'</td>
  </tr>
  <tr>
    <td valign="top"><div align="left"><strong>Town / City</strong></div></td>
    <td valign="top">'.$_POST['gedghethth'].'</td>
  </tr>
  <tr>
    <td valign="top"><div align="left"><strong>Enquiry</strong></div></td>
    <td valign="top">'.$_POST['rervberer323'].'</td>
  </tr>
</table></td>
</tr>
</table>
';            
$headers  = "From: $from\r\n";
$headers .= "Content-type: text/html\r\n"; 
$success = mail($to, $subject, $sBodyNew, $headers);              
header('Location: http://www.domain.com/success.htm');  
?>

Upvotes: 2

Views: 18172

Answers (3)

Ben D
Ben D

Reputation: 14479

It depends on how you are submitting the form. Presuming that you're submitting the page itself, then at the top of the page add something like this:

<?php
$warnings = "";

if (isset($_POST)){ //if post variables have been sent then we validate
    if (!isset($_POST['name']) || trim($_POST['name'])==''){ //if the variable isn't set or if it's empty
       $warnings .= "<p>You must provide a name</p>";
    }
}

?>

and then, in the html of the page, where you'd want the warning to be displayed, you'd add:

<?php
echo $warning;
?>

Also, note my validate syntax: if (!isset($_POST['name']))... this will return true there is not variable $_POST['name'], whereas if(!$_POST['name]) will only return true if, at some point, you set $_POST['name'] = false;

Make you you keep in mind that ![item] means "item is false", !isset([item]) means "the variable doesn't exist, and [item]=='' means that the item exists, and that it's an empty string. These are all separate things.

Upvotes: 1

kba
kba

Reputation: 19466

As you mentioned, yes, JavaScript can be turned off - not just by spambots, by anybody. JavaScript is a client-side language, so the validation happens on the client-side. Basing security on hoping that your client does what you want, is bad. Never trust user input.

That being said, you're on the right path with your PHP validation, except doing a die() will cause your page to stop executing before you have even printed your form. A common way to do this is doing something like this

$errors = array();

if (strlen($_POST['name']) < 5)
    $errors[] = "Username not long enough.";
if (usernameAvailable($_POST['name']))
    $errors[] = "Username already taken.";
if (otherValidationRule())
    $errors[] = "Something else isn't right.";

if (sizeof($errors) > 0) {
    foreach($errors as $error)
    {
        printf("<li>%s</li>", $error);
    }
}
else {
    print "Your data is OK!";
    // Do whatever you want with the data.
}

This will print "Your data is OK!" if nothing is wrong with the user input, otherwise it will print a list of all errors encountered. That could be something like

  • Username not long enough.
  • Something else isn't right.

Getting just one error at a time gives a bad user experience, as you might end up having to submit your form 5 times, because every time you fix one thing, a new error comes up.

Upvotes: 4

Vyktor
Vyktor

Reputation: 20997

If you're using the same page for multiple form, the best way would be adding hidden input:

<input type='hidden' name='action' value='sendMail' />

Than in PHP:

if( isset( $_POST['action'])){
    switch( $_POST['action'])){
        case 'sendMail':
            $msg = check_my_mail_form();
            if( $msg !== null){
                echo "Failed to send...";
            }
    }
}

function check_my_mail_form() {
    if( !isset( ...){
        return 'Please fill name';
    }
    return null;
}

Of course you should use different and little more complicated object oriented design (such as class with methods as validate() and getError()), but this should be good place to start for you.

Upvotes: 1

Related Questions