Jump to content
VTXmom

Required fields

Recommended Posts

It's me again, with another question. I have a form that I want to make some of the fields required, and some optional so that when the form is submitted, it a required field is empty, it displays an error. But, this is not happening, if I submit the form leaving required fields empty, it is still submitting. This is a class assignment(due EOD Friday), am I on the right track with my code? Thanks for all the help I have been getting with this project.

<?php
// define variables and set to empty values
$firstnameErr = $lastnameErr = $addressErr = $cityErr = $stateErr = $zipError = $phonenumberErr = $emailErr = $pettypeErr = $breedErr = $petnameErr = $neuteredorspayedErr = $petbirthday  = "";

$firstname = $lastname = $address = $city = $state = $zip = $phonenumber = $email = $pettype = $breed = $petname = $neuteredorspayed = $petbirthday =  "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  if (empty($_POST["FirstName"])) {
    $firstnameErr = "First name is required";
  } else {
    $firstname = ($_POST["FirstName"]);
  }
  
  if (empty($_POST["LastName"])) {
    $lastnameErr = "Last name is required";
  } else {
    $lastname =($_POST["LastName"]);
  }
  
  if (empty($_POST["Address"])) {
    $addressErr = "Address is required";
  } else {
    $address = ($_POST["Address"]);
  }
  
  if (empty($_POST["City"])) {
    $cityErr = "City is required";
  } else {
    $city = ($_POST["City"]);
  }
  
if (empty($_POST["State"])) {
    $stateErr = "State is required";
  } else {
    $state = ($_POST["State"]);
  }
  
  if (empty($_POST["Zip"])) {
    $zipErr = "Zipcode is required";
  } else {
    $zip = ($_POST["Zip"]);
  }
  
  if (empty($_POST["PhoneNumber"])) {
    $phonenumberErr = "Phone number is required";
  } else {
    $phonenumber = ($_POST["PhoneNumber"]);
  }
  
  if (empty($_POST["Email"])) {
    $email = "";
  } else {
    $email = ($_POST["Email"]);
  }
  
  if (empty($_POST["PetType"])) {
    $pettypeErr = "Pet type is required.";
  } else {
    $pettype = ($_POST["PetType"]);
  }
  
  if (empty($_POST["Breed"])) {
    $breed = "";
  } else {
    $breed = ($_POST["Breed"]);
  }
  
  if (empty($_POST["PetName"])) {
    $petnameErr = "Pets name is required";
  } else {
    $petname = ($_POST["PetName"]);
  }

if (empty($_POST["NeuteredOrSpayed"])) {
    $neuteredorspayed = "";
  } else {
    $neuteredorspayed = ($_POST["NeuteredOrSpayed"]);
  }

  if (empty($_POST["PetBirthday"])) {
    $petbirthday = "";
  } else {
    $petbirthday = ($_POST["PetBirthday"]);
   }
 }
 ?>

<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
 <title>Sandy's Pet Shop</title>
<link href="style.css" rel="stylesheet" type="text/css">
<div id="container">
<?php
    require 'header.php';
?>
</div>
</head>

<body>
<div>
<h3 align="center">Our Services</h3>
</div>
<div>
<p> We provide hands-on care and a variety of dog grooming services. First, choose a bath or full groom, then customize your dog's salon experience with a personalized add-on package. We also offer walk-in services that are available without an appointment.

Bring your dog into our salon for a free consultation! Our academy-trained groomers will personally meet with you to discuss your dog's specific needs. They'll also recommend just the right grooming service. Book an appointment today!</p>
</div>

<div>
<form method="post"id="form" action="submitform.php">
<input type="hidden" name="submitted" value="true"/>
    <table border="1">
    <tbody>
       <tr>
         <td>First Name:</td>
         <td><input name="FirstName" type="text" size="20">
         <span class="error">* Required</span>
         </td>
       </tr>
       <tr>
         <td>Last Name:</td>
         <td><input name="LastName" type="text" size="20">
         <span class="error">* Required</span>
         </td>
       </tr>
       <tr>
         <td>Address:</td>
         <td><input name="Address" type="text" size="20">
         <span class="error">* Required</span></span>
         </td>
       </tr>
       <tr>
          <td>City:</td>
          <td><input name="City" type="text" size="20">
          <span class="error">* Required</span></span>
          </td>
       </tr>
       <tr>
          <td>State:</td>
          <td><input name="State" type="text" size="15">
          <span class="error">* Required</span></span>
          </td>
       </tr>
       <tr>
          <td>Zipcode:</td>
          <td><input name="Zip" type="text" size="5">
          <span class="error">* Required</span></span>
          </td>
       </tr>
       <tr>
          <td>Phone Number:</td>
          <td><input name="PhoneNumber" type="text" size="15">
          <span class="error">* Required</span></span>
          </td>
       </tr>
       <tr>
          <td>Email Address:</td>
          <td><input name="Email" type="text" size="50"></td>
       </tr>
       <tr>
          <td>Pet Type</td>
          <td> 
               <select name="PetType">
    <option value="0">Please select</option>
    <option value="Cat">Cat</option>
    <option value="Dog">Dog</option>
          <span class="error">* Required</span>
          </td>
       </tr>
       <tr>
          <td>Dog Breed:</td>
          <td>
            <select name="Breed">
    <option value="0">Please select</option>
    <option value="PitBull">Pit Bull</option>
    <option value="Lab">Lab</option>
    <option value="Chihuaua">Chihuaua</option>
    <option value="Terrier">Terrier</option>
    <option value="German Shepherd">German Shepherd</option>
    <option value="Other">Other</option>
  </select>
  <span class="error">* Required if dog selected as pet type.</span>
          </td>
       </tr>
       <tr>
          <td>Pet Name:</td>
          <td><input name="PetName" type="text" size="15">
          <span class="error">* Required</span></span>
          </td>
       </tr>
       <tr>
          <td>Spayed/Neutered:</td>
          <td>Yes<input name="NeuteredOrSpayed" type="checkbox" value="1">
          No<input name="NeuteredOrSpayed" type="checkbox" value="0"></td>
        </tr>
        <tr>
           <td>Pet's Birthday:</td>
           <td><input name="PetBirthday" type="text"></td>
        </tr>
        <tr>
           <td>
             <input type="submit" value="Submit" name="submit"</input>
           </td>
         </tr>
       </tbody>
     </table>  
</form>

</body>
<hr>
<footer>
  <?php
    require 'footer.php';
?>
</div>
</footer>
</body>
</html>

Share this post


Link to post
Share on other sites

First off, don't just use empty() on the raw $_POST value. A user could just enter spaces into that field and it would pass the validation. Typically, you will want to use trim() on the value (to remove leading trailing white-space characters) before checking if it is empty.

 

The process you have is setting individual error variables for each field. That's pretty laborious. Plus, you would have to check ALL those variables individually. A better approach is to use an array to hold all the errors. If the array is empty then there are not errors. But, you aren't even checking those error variables later on. Otherwise the format of the code would work with the addition to check the errors. Here is a basic framework to follow

 

<?php
 
//Create variables for form validation tracking
$fields = array(); //Array to hold posted values to repopulate form
$errors = array(); //Array to hold errors
//Check if form was posted
if($_SERVER['REQUEST_METHOD']=='POST')
{
    //Validate POST values
 
    $fields['FirstName'] = isset($_POST['FirstName']) ? trim($_POST['FirstName']) : '';
    if(empty($fields['FirstName']))
    {
        $errors['FirstName'] = 'First name is required';
    }
 
    //Check if there were errors
    if(!count{$errors))
    {
        //There were no errors, process the data
 
        //After processing the data include or redirect to a success page
        //Exit this script to prevent the form from displaying agan
        exit();
    }
 
}
 
//Include form at bottom of script, add logic to re-popuated posted values and to display errors if they exist
?>
 
       <tr>
         <td>First Name:</td>
         <td><input name="FirstName" type="text" size="20" value="<?php if(isset($fields['FirstName']) { echo $fields['FirstName']; } ?>">
         <span class="error">* Required <?php if(isset($error['FirstName']) { echo $error['FirstName']; } ?></span>
         </td>
       </tr>
  • Like 1

Share this post


Link to post
Share on other sites

Thanks Psycho, I'm working on this right now, on the fields that I want to be optional, do I just leave out the error check and only write the code for the required fields?

$fields['FirstName'] = isset($_POST['FirstName']) ? trim($_POST['FirstName']) : '';
    if(empty($fields['FirstName']))
    {
        $errors['FirstName'] = 'First name is required';
    }

Share this post


Link to post
Share on other sites

In addition you could add a "required" attribute to the input fields in the form which will improve the user interface in those browsers that support it.

Share this post


Link to post
Share on other sites

 

Thanks Psycho, I'm working on this right now, on the fields that I want to be optional, do I just leave out the error check and only write the code for the required fields?

$fields['FirstName'] = isset($_POST['FirstName']) ? trim($_POST['FirstName']) : '';
    if(empty($fields['FirstName']))
    {
        $errors['FirstName'] = 'First name is required';
    }

The way I set it up, you would still want the code to define the values for the fields

 

$fields['OptionalField'] = isset($_POST['OptionalField']) ? trim($_POST['OptionalField']) : '';

 

That is needed to repopulate the form with the submitted values when an error does occur.

Share this post


Link to post
Share on other sites

I think I did something wrong, I am now getting this error: Parse error: syntax error, unexpected '{' in C:\xampp-win32-1.8.3-5-VC11\xampp\htdocs\pet-shop\grooming.php on line 80

I have checked for mismatched or missing tags and can't find anything, but I am wondering if I wrote the syntax correctly for the select lists?

<?php
//Create variables for form validation tracking
$errors = array($firstnameErr, $lastnameErr, $addressErr, $cityErr, $stateErr, $zipError, $phonenumberErr, $emailErr, $pettypeErr, $breedErr, $petnameErr, $neuteredorspayedErr, $petbirthday);

$fields = array($firstname, $lastname, $address, $city, $state, $zip, $phonenumber, $email, $pettype, $breed, $petname, $neuteredorspayed, $petbirthday);

//Check if form was posted
if ($_SERVER["REQUEST_METHOD"] == "POST") {

//Validate POST values
  $fields['FirstName'] = isset($_POST['FirstName']) ? trim($_POST['FirstName']) : '';
    if(empty($fields['FirstName']))
    {
        $errors['FirstName'] = 'First name is required';
    }
  
  $fields['LastName'] = isset($_POST['LastName']) ? trim($_POST['LastName']) : '';
    if(empty($fields['LastName']))
    {
        $errors['LastName'] = 'Last name is required';
    }
  
  $fields['Address'] = isset($_POST['Address']) ? trim($_POST['Address']) : '';
    if(empty($fields['Address']))
    {
        $errors['Address'] = 'Address is required';
    }
  
  $fields['City'] = isset($_POST['City']) ? trim($_POST['City']) : '';
    if(empty($fields['City']))
    {
        $errors['City'] = 'City is required';
    }
  
$fields['State'] = isset($_POST['State']) ? trim($_POST['State']) : '';
    if(empty($fields['State']))
    {
        $errors['State'] = 'State is required';
    }
  
  $fields['Zip'] = isset($_POST['Zip']) ? trim($_POST['Zip']) : '';
    if(empty($fields['Zip']))
    {
        $errors['Zip'] = 'Zip is required';
    }
  
 $fields['PhoneNumber'] = isset($_POST['PhoneNumber']) ? trim($_POST['PhoneNumber']) : '';
    if(empty($fields['PhoneNumber']))
    {
        $errors['PhoneNumber'] = 'PhoneNumber is required';
    }
  
  $fields['Email'] = isset($_POST['Email']) ? trim($_POST['Email']) : '';
    
  
 $fields['PetType'] = isset($_POST['PetType']) ? trim($_POST['PetType']) : '';
    if(empty($fields['PetType']))
    {
        $errors['PetType'] = 'Select type of pet';
    }
  
 $fields['Breed'] = isset($_POST['Breed']) ? trim($_POST['Breed']) : '';
   
  
  $fields['PetName'] = isset($_POST['PetName']) ? trim($_POST['PetName']) : '';
    if(empty($fields['PetName']))
    {
        $errors['PetName'] = 'PetName is required';
    }

$fields['NeuteredOrSpayed'] = isset($_POST['NeuteredOrSpayed']) ? trim($_POST['NeuteredOrSpayed']) : '';
   
$fields['PetBirthday'] = isset($_POST['PetBirthday']) ? trim($_POST['PetBirthday']) : '';
    if(empty($fields['PetBirthday']))
    {
        $errors['PetBirthday'] = 'Pet Birthday is optional';
    }
	
	 //Check if there were errors
    if(!count{$errors))
}   
 ?>

<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
 <title>Sandy's Pet Shop</title>
<link href="style.css" rel="stylesheet" type="text/css">
<div id="container">
<?php
    require 'header.php';
?>
</div>
</head>

<body>
<div>
<h3 align="center">Our Services</h3>
</div>
<div>
<p> We provide hands-on care and a variety of dog grooming services. First, choose a bath or full groom, then customize your dog's salon experience with a personalized add-on package. We also offer walk-in services that are available without an appointment.

Bring your dog into our salon for a free consultation! Our academy-trained groomers will personally meet with you to discuss your dog's specific needs. They'll also recommend just the right grooming service. Book an appointment today!</p>
</div>

<div>
<form method="post"id="form" action="submitform.php">
<input type="hidden" name="submitted" value="true"/>
    <table border="1">
    <tbody>
       <tr>
         <td>First Name:</td>
         <td><input name="FirstName" type="text" size="20" value="<?php if(isset($fields['FirstName']) { echo $fields['FirstName']; } ?>">
         <span class="error">* Required <?php if(isset($error['FirstName']) { echo $error['FirstName']; } ?></span>
         </td>
       </tr>
       <tr>
         <td>Last Name:</td>
         <td><input name="LastName" type="text" size="20" value="<?php if(isset($fields['LastName']) { echo $fields['FirstName']; } ?>">
         <span class="error">* Required <?php if(isset($error['LastName']) { echo $error['LastName']; } ?></span>
         </td>
       </tr>
       <tr>
         <td>Address:</td>
         <td><input name="Address" type="text" size="20" value="<?php if(isset($fields['Address']) { echo $fields['Address']; } ?>">
         <span class="error">* Required <?php if(isset($error['Address']) { echo $error['Address']; } ?></span>
         </td>
       </tr>
       <tr>
          <td>City:</td>
          <td><input name="City" type="text" size="20" value="<?php if(isset($fields['City']) { echo $fields['State']; } ?>">
         <span class="error">* Required <?php if(isset($error['City']) { echo $error['City']; } ?></span>
          </td>
       </tr>
       <tr>
          <td>State:</td>
          <td><input name="State" type="text" size="15" value="<?php if(isset($fields['State']) { echo $fields['State']; } ?>">
         <span class="error">* Required <?php if(isset($error['State']) { echo $error['State']; } ?></span>
          </td>
       </tr>
       <tr>
          <td>Zipcode:</td>
          <td><input name="Zip" type="text" size="5" value="<?php if(isset($fields['Zip']) { echo $fields['Zip']; } ?>">
         <span class="error">* Required <?php if(isset($error['Zip']) { echo $error['Zip']; } ?></span>
          </td>
       </tr>
       <tr>
          <td>Phone Number:</td>
          <td><td><input name="PhoneNumber" type="text" size="5" value="<?php if(isset($fields['PhoneNumber']) { echo $fields['PhoneNumber']; } ?>">
         <span class="error">* Required <?php if(isset($error['PhoneNumber']) { echo $error['PhoneNumber']; } ?></span>
          </td>
          </td>
       </tr>
       <tr>
          <td>Email Address:</td>
          <td><input name="Email" type="text" size="50"value="<?php if(isset($fields['Email']) { echo $fields['Email']; } ?>"></td>
       </tr>
       <tr>
          <td>Pet Type:</td>
          <td> 
               <select name="PetType" value="<?php if(isset($fields['PetType']) { echo $fields['PetType']; } ?>">
         <span class="error">* Required value="<?php if(isset($error['PetType']) { echo $error['PetType']; }" ?></span>
    <option value="0">Please select</option>
    <option value="Cat">Cat</option>
    <option value="Dog">Dog</option>
           </td>
       </tr>
       <tr>
          <td>Dog Breed:</td>
          <td>
            <select name="Breed"value="<?php if(isset($fields['Breed']) { echo $fields['Breed']; } ?>">
    <option value="0">Please select</option>
    <option value="PitBull">Pit Bull</option>
    <option value="Lab">Lab</option>
    <option value="Chihuaua">Chihuaua</option>
    <option value="Terrier">Terrier</option>
    <option value="German Shepherd">German Shepherd</option>
    <option value="Other">Other</option>
  </select>
           </td>
       </tr>
       <tr>
          <td>Pet Name:</td>
          <td><input name="PetName" type="text" size="15" value="<?php if(isset($fields['PetName']) { echo $fields['PetName']; } ?>">
         <span class="error">* Required <?php if(isset($error['PetName']) { echo $error['PetName']; } ?></span>
          </td>
       </tr>
       <tr>
          <td>Spayed/Neutered:</td>
          <td>Yes<input name="NeuteredOrSpayed" type="checkbox" value="1"<?php if(isset($fields['NeuteredOrSpayed']) { echo $fields['NeuteredOrspayed']; } ?>>
          No<input name="NeuteredOrSpayed" type="checkbox" value="0"<?php if(isset($fields['NeuteredOrSpayed']) { echo $fields['NeuteredOrSpayed']; } ?>></td>
        </tr>
        <tr>
           <td>Pet's Birthday:</td>
           <td><input name="PetBirthday" type="text" value="<?php if(isset($fields['PetBirthday']) { echo $fields['PetBirthday']; } ?>"></td>
        </tr>
        <tr>
           <td>
             <input type="submit" value="Submit" name="submit"</input>
           </td>
         </tr>
       </tbody>
     </table>  
</form>

</body>
<hr>
<footer>
  <?php
    require 'footer.php';
?>
</div>
</footer>
</body>
</html>

Share this post


Link to post
Share on other sites

You used a curly brace by accident here

 

if(!count{$errors))

 

Plus, that if() condition isn't doign anything. At least add the curly braces for the code-block that you will eventually add

 

if(!count($errors))
{
    //No validation errors, process the data
}

 

Lastly, use COMMENTS! You will save hours of time in the future when you have to debug code. Even for the validation code I would add a comment for each field with something such as

 

 

//Validate that last name is not empty

 

or

 

 

//Get neutered or spayed value, no validation

 

It may seem like wasted content, but it isn't. You likely copy/pasted code for each field. If you accidentally leave out validation for a field or add it for a field you may come back later and scratch your head as to why you did it. If you added a comment as to what you are trying to do it will be obvious that it was a mistake.

Share this post


Link to post
Share on other sites

What is this?

 

//Create variables for form validation tracking
$errors = array($firstnameErr, $lastnameErr, $addressErr, $cityErr, $stateErr, $zipError, $phonenumberErr, $emailErr, $pettypeErr, $breedErr, $petnameErr, $neuteredorspayedErr, $petbirthday);
 
$fields = array($firstname, $lastname, $address, $city, $state, $zip, $phonenumber, $email, $pettype, $breed, $petname, $neuteredorspayed, $petbirthday);

 

Those variables you are putting into the arrays don't exist. You are only creating an array with a bunch of NULL elements that have no purpose. That wasn't what I posted, so I don't know why you did that. The code for the validation logic will add the necessary elements to the arrays. In fact, doing that with the $errors array will only make the code fail validation every single time since count($errors) will always be > 0

Share this post


Link to post
Share on other sites

Some other things.

 

You can't set the value of a select list in the <select> tag. You need to set the appropriate option to selected. Also, you should add logic in the validation code to verify that the value passed for a select filed is an acceptable value. You can create an array for the select list values and use that to 1) create the select lists (with the selected option) and 2) for validating the passed value.

 

2. Don't put a <span> inside a select field. Put it before the opening <select> tag or after the closing </select> tag. And, don't forget to use the closing select tag!

 

3. You wouldn't use the same logic to set the value of a checkbox. A checkbox is either checked or not. It is different from other form fields in that the field is only passed in the post data if it was checked. So, you would set the checked status based on whether the field was passed or not.

 

4. Don't use checkboxes for multiple options when the user is only supposed to select one value. Use a radio group instead. Giving them the same name won't even work (unless you make them an array, but that's for a different purpose).

 

I made a slight change to the workflow of the code to simplify things. Instead of setting the field values int he validation logic, you can instead set them at the top of the page based upon whether the values were posted or not. This way, the code in the form to set the values can just use a simple echo instead of an if() statement.

 

I also fixed some of the issues above. But, I want you to make an attempt at creating an array for the select lists and creating code to 1) create the select lists and 2) use the array to validate the posted values. Create the arrays so the value is the key and the label is the value. You may be using the same for both, but that is not typically the case. E.g.:

$breeds = array(
    'PitBull' => 'PitBull',
    'Lab' => 'Lab',
    'Chihuaua' => 'Chihuaua'
);

Revised code

<?php
//Create variables for form validation tracking
$errors = array();
$fields = array();
 
//Set field values based on posted data (if sent)
$fields['FirstName']   = isset($_POST['FirstName'])   ? trim($_POST['FirstName']) : '';
$fields['LastName']    = isset($_POST['LastName'])    ? trim($_POST['LastName']) : '';
$fields['Address']     = isset($_POST['Address'])     ? trim($_POST['Address']) : '';
$fields['City']        = isset($_POST['City'])        ? trim($_POST['City']) : '';
$fields['State']       = isset($_POST['State'])       ? trim($_POST['State']) : '';
$fields['Zip']         = isset($_POST['Zip'])         ? trim($_POST['Zip']) : '';
$fields['PhoneNumber'] = isset($_POST['PhoneNumber']) ? trim($_POST['PhoneNumber']) : '';
$fields['Email']       = isset($_POST['Email'])       ? trim($_POST['Email']) : '';
$fields['PetType']     = isset($_POST['PetType'])     ? trim($_POST['PetType']) : '';
$fields['Breed']       = isset($_POST['Breed'])       ? trim($_POST['Breed']) : '';
$fields['PetName']     = isset($_POST['PetName'])     ? trim($_POST['PetName']) : '';
$fields['NeuteredOrSpayed'] = isset($_POST['NeuteredOrSpayed']) ? trim($_POST['NeuteredOrSpayed']) : '';
$fields['PetBirthday'] = isset($_POST['PetBirthday']) ? trim($_POST['PetBirthday']) : '';
 
//Check if form was posted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
 
    //Validate required values
    if(empty($fields['FirstName']))
    {
        $errors['FirstName'] = 'First name is required';
    }
    if(empty($fields['LastName']))
    {
        $errors['LastName'] = 'Last name is required';
    }
    if(empty($fields['Address']))
    {
        $errors['Address'] = 'Address is required';
    }
    if(empty($fields['City']))
    {
        $errors['City'] = 'City is required';
    }
    if(empty($fields['State']))
    {
        $errors['State'] = 'State is required';
    }
    if(empty($fields['Zip']))
    {
        $errors['Zip'] = 'Zip is required';
    }
    if(empty($fields['PhoneNumber']))
    {
        $errors['PhoneNumber'] = 'PhoneNumber is required';
    }
    if(empty($fields['PetType']))
    {
        $errors['PetType'] = 'Select type of pet';
    }
    if(empty($fields['PetName']))
    {
        $errors['PetName'] = 'PetName is required';
    }
    if(empty($fields['PetBirthday']))
    {
        $errors['PetBirthday'] = 'Pet Birthday is optional';
    }
 
//Check if there were errors
    if(!count($errors))
    {
        //Add logic to process the form data    
        //Include or redirect to success page
        echo "Validation passed."; //Temporary message for debugging purposes
        exit();
    }
}   
 ?>
 
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
 <title>Sandy's Pet Shop</title>
<link href="style.css" rel="stylesheet" type="text/css">
<div id="container">
<?php
    require 'header.php';
?>
</div>
</head>
 
<body>
<div>
<h3 align="center">Our Services</h3>
</div>
<div>
<p> We provide hands-on care and a variety of dog grooming services. First, choose a bath or full groom, then customize your dog's salon experience with a personalized add-on package. We also offer walk-in services that are available without an appointment.
 
Bring your dog into our salon for a free consultation! Our academy-trained groomers will personally meet with you to discuss your dog's specific needs. They'll also recommend just the right grooming service. Book an appointment today!</p>
</div>
 
<div>
<form method="post"id="form" action="submitform.php">
<input type="hidden" name="submitted" value="true"/>
    <table border="1">
    <tbody>
       <tr>
         <td>First Name:</td>
         <td><input name="FirstName" type="text" size="20" value="<?php echo $fields['FirstName']; ?>">
         <span class="error">* Required <?php if(isset($error['FirstName']) { echo $error['FirstName']; } ?></span>
         </td>
       </tr>
       <tr>
         <td>Last Name:</td>
         <td><input name="LastName" type="text" size="20" value="<?php echo $fields['FirstName']; ?>">
         <span class="error">* Required <?php if(isset($error['LastName']) { echo $error['LastName']; } ?></span>
         </td>
       </tr>
       <tr>
         <td>Address:</td>
         <td><input name="Address" type="text" size="20" value="<?php echo $fields['Address']; ?>">
         <span class="error">* Required <?php if(isset($error['Address']) { echo $error['Address']; } ?></span>
         </td>
       </tr>
       <tr>
          <td>City:</td>
          <td><input name="City" type="text" size="20" value="<?php echo $fields['State']; ?>">
         <span class="error">* Required <?php if(isset($error['City']) { echo $error['City']; } ?></span>
          </td>
       </tr>
       <tr>
          <td>State:</td>
          <td><input name="State" type="text" size="15" value="<?php echo $fields['State']; ?>">
         <span class="error">* Required <?php if(isset($error['State']) { echo $error['State']; } ?></span>
          </td>
       </tr>
       <tr>
          <td>Zipcode:</td>
          <td><input name="Zip" type="text" size="5" value="<?php echo $fields['Zip']; ?>">
         <span class="error">* Required <?php if(isset($error['Zip']) { echo $error['Zip']; } ?></span>
          </td>
       </tr>
       <tr>
          <td>Phone Number:</td>
          <td><td><input name="PhoneNumber" type="text" size="5" value="<?php echo $fields['PhoneNumber']; ?>">
         <span class="error">* Required <?php if(isset($error['PhoneNumber']) { echo $error['PhoneNumber']; } ?></span>
          </td>
          </td>
       </tr>
       <tr>
          <td>Email Address:</td>
          <td><input name="Email" type="text" size="50"value="<?php echo $fields['Email']; ?>"></td>
       </tr>
       <tr>
          <td>Pet Type:</td>
          <td> 
              <select name="PetType">
              <option value="0">Please select</option>
              <option value="Cat">Cat</option>
              <option value="Dog">Dog</option>
              </select>
              <span class="error">* Required value="<?php if(isset($error['PetType']) { echo $error['PetType']; } ?></span>
          </td>
       </tr>
       <tr>
          <td>Dog Breed:</td>
          <td>
            <select name="Breed">
            <option value="0">Please select</option>
            <option value="PitBull">Pit Bull</option>
            <option value="Lab">Lab</option>
            <option value="Chihuaua">Chihuaua</option>
            <option value="Terrier">Terrier</option>
            <option value="German Shepherd">German Shepherd</option>
            <option value="Other">Other</option>
            </select>
           </td>
       </tr>
       <tr>
          <td>Pet Name:</td>
          <td><input name="PetName" type="text" size="15" value="<?php echo $fields['PetName']; ?>">
         <span class="error">* Required <?php if(isset($error['PetName']) { echo $error['PetName']; } ?></span>
          </td>
       </tr>
       <tr>
          <td>Spayed/Neutered:</td>
          <td>
            Yes<input name="NeuteredOrSpayed" type="radio" value="1" <?php if($fields['NeuteredOrSpayed']=='1') { echo 'checked="checked"' } ?>>
            No<input name="NeuteredOrSpayed" type="radio" value="0" <?php if($fields['NeuteredOrSpayed']=='0') { echo 'checked="checked"' } ?>>
          </td>
        </tr>
        <tr>
           <td>Pet's Birthday:</td>
           <td><input name="PetBirthday" type="text" value="<?php echo $fields['PetBirthday']; ?>"></td>
        </tr>
        <tr>
           <td colspan="2">
             <input type="submit" value="Submit" name="submit"</input>
           </td>
         </tr>
       </tbody>
     </table>  
</form>
 
</body>
<hr>
<footer>
<?php
    require 'footer.php';
?>
</div>
</footer>
</body>
</html>
Edited by Psycho

Share this post


Link to post
Share on other sites

Psycho,

I want to thank you so much for your help and patience with me. I  had trouble getting the select list to work, so I scrapped what I was doing and started completely over. I read over what you had posted and went back to the validation lessons in my textbook and I got it to work!  I wanted to post my code to show you what I came up with.

<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
 <title>Sandy's Pet Shop</title>
<link href="style.css" rel="stylesheet" type="text/css">
<div id="container">


<script type="text/javascript">

function checkLength(text, min, max) {
min = min || 1;
max = max || 1000;

if (text.length < min || text.length > max) {
	return false;
}
return true;
}

function validate(form) {
var FirstName = form.FirstName.value;
var LastName = form.LastName.value;
var Address = form.Address.value;
var City = form.City.value;
var State = form.State.value;
var Zip = form.Zip.value;
var PhoneNumber = form.State.value;
var PetType = form.PetType.value;
var PetName = form.PetName.value;
var errors = [];

//validate that a pet type is chosen

if (!checkSelect(form.PetType) ) {
  errors[errors.length] = "Please select a pet type.";
}

//validate that no required fields are empty

if (!checkLength(FirstName)) {
   errors[errors.length] = "First name is required.";
}

if (!checkLength(LastName)) {
   errors[errors.length] = "Last name is required.";
}

if (!checkLength(Address)) {
   errors[errors.length] = "Address is required.";
}

if (!checkLength(City)) {
   errors[errors.length] = "City is required.";
}

if (!checkLength(State)) {
   errors[errors.length] = "State is required.";
}

if (!checkLength(Zip)) {
   errors[errors.length] = "Zipcode is required.";
}

if (!checkLength(PhoneNumber)) {
   errors[errors.length] = "PhoneNumber is required.";
}

if (!checkLength(PetType)) {
   errors[errors.length] = "Pet type is required.";
}

if (!checkLength(PetName)) {
   errors[errors.length] = "Pet name is required.";
}

if (errors.length > 0) {
   reportErrors(errors);
   return false;
   }
   return true;
   }

//checkSelect helper function to make sure first option is not selected

function checkSelect(select) {
  return (select.selectedIndex > 0);
}   
   
function reportErrors(errors) {
var msg = "Please try again.";
var numError;
for (var i = 0; i<errors.length; i++) {
   numError = i + 1;
   msg +=  numError + ". " + errors[i];
}
alert(msg);
}
</script>
<?php
    require 'header.php';
?>
</div>
</head>

<body>
<div>
<h3 align="center">Our Services</h3>
</div>
<div>
<p> We provide hands-on care and a variety of dog grooming services. First, choose a bath or full groom, then customize your dog's salon experience with a personalized add-on package. We also offer walk-in services that are available without an appointment.

Bring your dog into our salon for a free consultation! Our academy-trained groomers will personally meet with you to discuss your dog's specific needs. They'll also recommend just the right grooming service. Book an appointment today!</p>
</div>

<div>
<form method="post"id="form"  onSubmit="return validate(this);"action="submitform.php">
<input type="hidden" name="submitted" value="true"/>
    <table border="1">
    <tbody>
       <tr>
         <td>First Name:</td>
         <td><input name="FirstName" type="text" size="20" >
         <span class="error">* Required</span>
         </td>
       </tr>
       <tr>
         <td>Last Name:</td>
         <td><input name="LastName" type="text" size="20" >
         <span class="error">* Required</span>
         </td>
       </tr>
       <tr>
         <td>Address:</td>
         <td><input name="Address" type="text" size="20">
         <span class="error">* Required </span>
         </td>
       </tr>
       <tr>
          <td>City:</td>
          <td><input name="City" type="text" size="20" >
         <span class="error">* Required </span>
          </td>
       </tr>
       <tr>
          <td>State:</td>
          <td><input name="State" type="text" size="15" >
         <span class="error">* Required </span>
          </td>
       </tr>
       <tr>
          <td>Zipcode:</td>
          <td><input name="Zip" type="text" size="5" >
         <span class="error">* Required </span>
          </td>
       </tr>
       <tr>
          <td>Phone Number:</td>
          <td><input name="PhoneNumber" type="text" size="15">
         <span class="error">* Required</span>
          </td>
          </td>
       </tr>
       <tr>
          <td>Email Address:</td>
          <td><input name="Email" type="text" size="50"></td>
       </tr>
       <tr>
          <td>Pet Type:</td>
          <td> 
               <select name="PetType">
         <span class="error">* Required value</span>
    <option value="0">Please select</option>
    <option value="Cat">Cat</option>
    <option value="Dog">Dog</option>
           </td>
       </tr>
       <tr>
          <td>Dog Breed:</td>
          <td>
            <select name="Breed">
    <option value="0">Please select</option>
    <option value="PitBull">Pit Bull</option>
    <option value="Lab">Lab</option>
    <option value="Chihuaua">Chihuaua</option>
    <option value="Terrier">Terrier</option>
    <option value="German Shepherd">German Shepherd</option>
    <option value="Other">Other</option>
  </select>
           </td>
       </tr>
       <tr>
          <td>Pet Name:</td>
          <td><input name="PetName" type="text" size="15" >
         <span class="error">* Required </span>
          </td>
       </tr>
       <tr>
          <td>Spayed/Neutered:</td>
          <td>Yes<input name="NeuteredOrSpayed" type="checkbox" value="1">
          No<input name="NeuteredOrSpayed" type="checkbox" value="0"</td>
        </tr>
        <tr>
           <td>Pet's Birthday:</td>
           <td><input name="PetBirthday" type="text"</td>
        </tr>
        <tr>
           <td>
             <input type="submit" value="Submit" name="submit"</input>
           </td>
         </tr>
       </tbody>
     </table>  
</form>

</body>
<hr>
<footer>
  <?php
    require 'footer.php';
?>
</div>
</footer>
</body>
</html>

I know there was probably a prettier way to do this, and I intend to work on this a lot more on my own time. I just want to thank you again for your help.

Edited by VTXmom

Share this post


Link to post
Share on other sites

Well, you changed from PHP logic to do the validation to just JavaScript. Doing validation on the client (i.e. JavaScript) is optional. But, you must perform validation on the server (i.e. PHP). The reason is it is a very simple process for someone to sidestep JavaScript validation and submit any data they want to the server. If you don't have server-side validation a person could potentially submit data that could compromise your application.

Share this post


Link to post
Share on other sites

What Psycho said, is true. Client Side validation is always dangerous. But Server side also can bring some trouble if you don't take proper guard. :)

I just thought how it would be to use a very simple 'Validate' class. I used trait and interface so that you could hook more functionality later. First the validate.php code:

<?php

/* 
 * .
 */

trait ValidateTrait {    
    public function checked() {    
        return "Okay, Your Data has been saved";
    }
    public function unchecked() {    
        return "You have not provided proper data.";
    }
}

interface ValidateInterface {
    public function make($value);
}

class Validate implements ValidateInterface {
    use ValidateTrait;
    
    public $_value = array();

    public function make($value) {       
        
        $this->_value = $value;
        
        if (strlen($value) === 0 || strlen($value) < 3 || strlen($value) > {
            return FALSE;            
        }
        elseif(is_string($value) && trim($value) === ''){
            return FALSE;
        }
        elseif (is_array($value)) {
            return FALSE;           
        }
        
        elseif (preg_match("/\@.\/i", $value)) {
            return FALSE;
        }
                
        return TRUE;        
    }    
}

 

Second the form.php:

<form method="POST" action="action.php" accept-charset="UTF-8">
        <input name="_token" type="hidden" value="EMnZhqPbryk7oVPcrjwxuTrlHto">

<label for="username">Your Name</label>
<p>
<input name="username" type="text" value="Your name" id="username">
<p>

<label for="email">Your Email</label>
<p>
<input name="email" type="text" value="your email" id="email">
<p>
<input type="submit" value="Register">


</form>
 

and finally the action.php where I put the message of validation:

<?php

/* 
 * 
 */
require 'validate.php';

if ($_POST['_token'] === "EMnZhqPbryk7oVPcrjwxuTrlHto"){
    
    $value = [$_POST['username'], $_POST['email']];
    $validate = new Validate();
    if ($validate->make($value[0]) && $validate->make($value[1])){
        echo $validate->checked();
    }
    else {
        echo $validate->unchecked();
    }    
}
 else {
     
    echo 'You Crackers! Go back!';
    
}
 

You can obviously add many more fields to it as you need. I just checked username and email. username field can not be blank, and between 3 to 8 characters etc.

Best wishes to all.

Edited by Sanjib Sinha

Share this post


Link to post
Share on other sites

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.