2

I want to validate my form so ALL of the fields are required. If a field is NOT inserted or left blank it will display an error message AFTER submission. Could anyone help?

Form

<html>  
<head>  
<title>Form Input Data</title> 
</head>
<table>  
<body><table border="1">
<table bgcolor="lightblue"></body>

     <form method="post" action="insert_ac.php"> 
    <br>
<tr><td align="left"><strong>Nurse Information</strong></td></tr>
<tr>
<td><font color="red">Please select your name</font></td>
</tr>
<tr>
<td>Fullname</td>
<td><select name="valuelist">;
<option value="valuelist" name="nurse_name" value='<?php echo $nurse_name;  ?>'></option>
<?php
$value=$_POST ["valuelist"];
$con = mysql_connect("localhost","root","") or die('Could not connect:'.mysql_error());
mysql_select_db("a&e", $con) or die('Could not select database.');

$fetch_nurse_name = mysql_query("SELECT DISTINCT Fullname FROM nurse");

while($throw_nurse_name = mysql_fetch_array($fetch_nurse_name)) {
echo '<option   value=\"'.$throw_nurse_name[0].'">'.$throw_nurse_name[0].'</option>';
 }
 echo "</select>";

?>
</td>
</tr>
<tr>
<td>Please register name here:</td>
<tr>  

        <td>Fullname</td>

       <td><input type="text" name="nurse_forename" size="30"> </td>

     </tr>
 </tr>
user2075528
  • 55
  • 2
  • 2
  • 5

7 Answers7

4

I would do something like this:

$req = ['field1', 'field2', 'field...'];
$status = true;
foreach ($req as $field) {
    if (empty($_POST[$field])) {
        echo 'Field ' . $field . ' is empty';
        $status = false;
    }
}
if ($status) {
    // ok
} else {
    // not okay!
}

You create an array ($req), with all field names and loop over them. Check every field against empty() (check the php manual for this function).

Here is a better (and mostly) correct HTML snippet... Please indent properly and read any HTML tutorial for well formed code. Your HTML is **.

<?php

$value=$_POST["valuelist"];
$con = mysql_connect("localhost","root","") or die('Could not connect:'.mysql_error());
mysql_select_db("a&e", $con) or die('Could not select database.');

$fetch_nurse_name = mysql_query("SELECT DISTINCT Fullname FROM nurse");

?>
<html>
<head>
    <title>Form Input Data</title> 
</head>
<body>

    <form method="post" action="insert_ac.php"> 

    <table border="1" bgcolor="lightblue">
        <tr>
            <td align="left"><strong>Nurse Information</strong></td>
        </tr>
        <tr>
            <td><font color="red">Please select your name</font></td>
        </tr>
        <tr>
            <td>Fullname</td>
            <td>
                <select name="valuelist">
                    <option value="valuelist" value="<?php echo $nurse_name;  ?>"></option>
                    <?php

                    while($throw_nurse_name = mysql_fetch_array($fetch_nurse_name)) {
                        echo '<option value="'.$throw_nurse_name[0].'">'.$throw_nurse_name[0].'</option>';
                    }
                    ?>
                </select>
            </td>
        </tr>
        <tr>
            <td>Please register name here:</td>
        </tr>
        <tr>  
            <td>Fullname</td>
            <td><input type="text" name="nurse_forename" size="30"> </td>
        </tr>
    </table>
    </form>
</body>
</html>

If you have only the two given fields, this would do it:

$status = false;
$name = '';

if (!empty($_POST['nurse_forename'])) {
    $name = $_POST['nurse_forename'];
    $status = true;

} elseif (!empty($_POST['valuelist'])) {
    $name = $_POST['valuelist'];
    $status = true;

} else {

    $status = false;
    // none of nurse_forname OR valuelist is filled
    // abort.
}
Nepomuk Pajonk
  • 2,972
  • 1
  • 19
  • 29
  • Would this work if the user DID NOT select a Forename from the database(select box left blank) and they are required to input a name instead? – user2075528 Feb 16 '13 at 21:55
  • No, this will check if ALL elements (in `$req`) are not empty. If you want to check if `valuelist` OR `nurse_forename` is submitted, you need to change it. But your HTML-Form is not designed for this, you need to change it too. – Nepomuk Pajonk Feb 16 '13 at 22:12
  • Please explain a bit more about what this form should do. If you have only these two form fields, the given solution is too complicated. I've added the way for only two fields. – Nepomuk Pajonk Feb 17 '13 at 14:48
1

Something like

foreach($_POST as $form_entry)
 if(empty($form_entry))
  echo 'you have to fill in all fields';
Marko D
  • 7,576
  • 2
  • 26
  • 38
1
   if (isset($_POST['variable']{0})) {
   echo 'I exist and I have at least one char!';
   else
   echo 'I dont exist or I have no chars!';

It checks whether $_POST['variable'] exists and has at least one char.

pamil
  • 980
  • 2
  • 10
  • 20
0

if($_POST['valuelist'] == NULL or $_POST['nurse_forename'] == NULL){ die('empty'); }

Untested.

Vlad
  • 795
  • 1
  • 12
  • 35
0

Try it this way:

if(empty($_POST['nurse_forename'])){
echo "Field Nurse-Forename is empty";
}

You also could check like this:

if($_POST['nurse_forename']==""){
echo "Nurse-Forename is empty";
}

You cannot check for all fields with one command (because you cannot distinct between one and more empty fields). You could do it a little more elegant using OOP, but I think for the code you posted above the example should do.

BNetz
  • 361
  • 4
  • 20
  • Would this work if the user DID NOT select a Forename from the database(select box left blank) and they are required to input a name instead? – user2075528 Feb 16 '13 at 21:51
  • Yes, if you check each field seperately it will work. You will have to play around with the operators and to check how both fields are sent. Or you give both fields the same name. – BNetz Feb 17 '13 at 00:17
0

Also You can try this, It's validating all form items.

if (isset ( $_POST ['submit_button_name'] )) {
    $validated = true;
    array_walk_recursive ( $_POST, function ($value, $key) {
        global $validated;
        if (! trim ( $value ))
            $validated = false;
    } );
    if ($validated) {
        // insert function and redirect
    } else {
        // print Your message
    }
}
// Your form 
Vahe Shadunts
  • 1,956
  • 14
  • 18
0
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>

<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST")
{

   if (empty($_POST["name"]))
     {$nameErr = "Name is required";}
   else
     {$name = test_input($_POST["name"]);}

   if (empty($_POST["email"]))
     {$emailErr = "Email is required";}
   else
     {$email = test_input($_POST["email"]);}

   if (empty($_POST["website"]))
     {$website = "";}
   else
     {$website = test_input($_POST["website"]);}

   if (empty($_POST["comment"]))
     {$comment = "";}
   else
     {$comment = test_input($_POST["comment"]);}

   if (empty($_POST["gender"]))
     {$genderErr = "Gender is required";}
   else
     {$gender = test_input($_POST["gender"]);}

}

function test_input($data)
{
     $data = trim($data);
     $data = stripslashes($data);
     $data = htmlspecialchars($data);
     return $data;
}
?>

<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
   Name: <input type="text" name="name">
   <span class="error">* <?php echo $nameErr;?></span>
   <br><br>
   E-mail: <input type="text" name="email">
   <span class="error">* <?php echo $emailErr;?></span>
   <br><br>
   Website: <input type="text" name="website">
   <span class="error"><?php echo $websiteErr;?></span>
   <br><br>
   Comment: <textarea name="comment" rows="5" cols="40"></textarea>
   <br><br>
   Gender:
   <input type="radio" name="gender" value="female">Female
   <input type="radio" name="gender" value="male">Male
   <span class="error">* <?php echo $genderErr;?></span>
   <br><br>
   <input type="submit" name="submit" value="Submit">
</form>

<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>

</body>
</html>