Mandatory form field issue

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
JustinLogan
Forum Newbie
Posts: 1
Joined: Tue Jan 18, 2011 11:00 pm

Mandatory form field issue

Post by JustinLogan »

Hello,

I searched the forum for this issue to no avail, hopefully this isn't a repeat:

I'm doing a very simple form to get mail. I just want three slots, one for someone's name, one for an email address, and one for their comments. I also want the email address and comments section to be mandatory. If I use this:

Code: Select all

$yourname = validation($_POST['yourname']);
$comments = validation($_POST['comments'], "Comment Required");
$email    = validation($_POST['email'], "Email Address Required");
Where Validation is

Code: Select all

<?php
function validation($data, $blank='')
{
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    if ($blank && strlen($data) == 0)
    {        
        die($blank);
    }
    
    return $data;
}
?>
It works PERFECTLY.

It is, however, very ugly. I want instead to redirect to another page identical to the form page but with the required words in red. So I made another page entitled concacte.php, and replaced the ugly words with header('location') tags as follows:

Code: Select all

$yourname = validation($_POST['yourname']);
$comments = validation($_POST['comments'], header('Location: ../index.php?entry=contacte'));
$email    = validation($_POST['email'], header('Location: ../index.php?entry=contacte'));
This directs me to the correct site, and it looks like I want it to, except it happens EVERY TIME, even when the fields are not left blank. I thought it wouldn't ever even see that portion of code unless the field is left blank, but now it goes there every time, blank or not. To add to my confusion, it works when I switch it back to just words, but not with the header(). I've fiddled with this for hours now to no avail, any advice?

Thank you in advance,
Justin
Peter Kelly
Forum Contributor
Posts: 143
Joined: Fri Jan 14, 2011 5:33 pm
Location: England
Contact:

Re: Mandatory form field issue

Post by Peter Kelly »

Just out of curiosity why don't you just change the function save repeating the code.

Code: Select all

function validation($data, $blank='')
{
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    if ($blank == 0 && strlen($data) == 0)
    {        
        header("Location: ../index.php?entry=contacte");
    }
    
    return $data;
}
and sometimes I find if you put the == 0 on both separately it works.
Post Reply