try/throw/catch to enforce date format

For this week’s assignment in class I’m asked to:

For this activity, you will create a quick form with the following fields:
First Name
Last Name
Date of Birth (using a mm/dd/yyyy format)
State
Zip Code

To continue the activity, please follow the steps below:

With the form created, create a PHP script that will take in the form values and process each value using a variable of a specific data type to best suit the commonly entered data for each field.

[b]Next, create a try/throw/catch statement in your script to handle any anticipated potential errors users may perform when entering information on the form and be sure to include information to provide to the user informing them of the error that has been performed along with suggested correction for the error. For example, you have entered an invalid value for the DOB field. The format for your DOB must be mm/dd/yyyy format[/b].</blockquote>

I’ve written a a basic html form to cover the assignment, and I’ve started my php by declaring my form variables, and setting data type for my zipcode to “int”.

Here’s where things get dicey…I wrote an if statement to check for numbers in the “$zip” field, since if anyone enters letters the return is 0 on the form, I wrote it to reflect that outcome. I’ll be turning this into a try/throw/catch statement to instead return an error. I’ve got a good idea how to do that, but I don’t even know how to get started on evaluating, and enforcing the date format.

I know that I’ll need to create an if statement around checking for a “” in the 3rd and 6th position and then building a try/throw/catch around that if statement…but I can’t figure out how to build the operation that evaluates that field. Here’s what I’ve written so far…it’s super simple, but all I’m going for is basic functionality.

This is my preheader php:
[php]<?php
// create short variable names
$firstname = $_POST[‘firstname’];
$lastname = $_POST[‘lastname’];
$dob = $_POST[‘dob’];
$state = $_POST[‘state’];
$zip = $_POST[‘zip’];
settype ($zip, ‘int’);
?>[/php]

And this is my body php:
[php]<?php // details the output the user sees upon submitting the form, which includes the date, and the user information submitted
echo "

Information processed: ";
echo “

$firstname”;
echo " $lastname
";
echo "$dob
";
echo " $state
";
echo "$zip
";
// early start on building error handling
if ($zip ==0)
echo ‘Invalid Zip Code Entered’;

?>[/php]

While I’m hoping and waiting for someone to help, I will be attempting to get that if statement into a try/trow/catch statement, but if anyone knows of a better format then please…I’ll take all the critique and help I can get.

I don’t really understand why this assignment wants me to throw an exception for an invalid date format, when most developers use a client side script to turn the user back around to the form page and highlight what they need to correct, but this is the assignment and I didn’t choose the example.

Thanks in advance for anyone patient enough to help me out with this.

Because you should always validate data server side as well. Validation done client side is just for making the users life easier, but this validation can not be trusted.

You should do something like this:

[php] <?php

try {
/*
* Fallback in case the post fields are empty. If they are posted empty then
* the script will throw notices about indexes not beeing set.
*/
$firstname = !empty($_POST[‘firstname’]) ? $_POST[‘firstname’] : null;
$lastname = !empty($_POST[‘lastname’]) ? $_POST[‘lastname’] : null;

if (!is_string($firstname)) {
throw new Exception (‘Invalid first name, it must be a string’);
}

if (!is_string($lastname)) {
throw new Exception (‘Invalid first name, it must be a string’);
}

/*
* Everything OK, include body.php here
* Remember to use htmlentities or similar to escape variables to avoid XSS
*/

} catch (Exception $e) {
/* The catch block should be at the very end of your script */
echo 'Error: ’ . $e->getMessage();
}

/* You shouldn’t end php files with ?> if you don’t have to. */[/php]

Hey Thanks for your reply, Jim. Since I’m taking a class I have to stick closely to the book and instruction, and the book calls for closing php tags “?>”. For future reference, what are the advantages of not using them?

Also, my exceptions for this week’s work have to be performed by using try/throw/catch blocks of code. For example, I set my data type for the $zip field as accepting only “int” so…

[php] // evaluates whether the zip code is in a valid format, if it isn’t, then it tells the user that the zip code entered was invalid if it’s not.
try{
if($zip ==O){
throw new Exception(‘Please enter a valid zip code’);
}else{
echo "$zip
";}

}catch(Exception $e){
  echo $e->getMessage() ."\n" ;[/php]

This works, because if anything other than a number is entered in that field then the return is “0”.
I want to write another one for the date, but I can’t figure out how to write the “if” statement to make sure the format is mm/dd/yyyy. Making sure the name fields are strings, that’s a great call and I’ll definitely experiment with adding them in, in the format the instructor wants.

Thanks for your time. I appreciate it.

Sounds like a good idea :slight_smile:

Well, for one they are just not necessary. It would be like asking for a reason not to start/stop php for each line of code.

A real reason not to do so is that you are prone to errors. If you have anything after a ?> (even a whitespace) php will parse it as output. If you later on in the code try to modify the headers (cookies, redirects, etc) it will fail, because the page has already started outputting, so the headers are sent.

[hr]

On topic

You could just search for something like “php validate mm/dd/yyyy” on google, there are plenty of ways to do this, but some of the easiest (?) would have to be to just create a datetime object and then compare it to the original value and see if they match.

[php]<?php
date_default_timezone_set(‘Europe/Oslo’);

try {
/*
* Fallback in case the post fields are empty. If they are posted empty then
* the script will throw notices about indexes not beeing set.
*/
$firstname = !empty($_POST[‘firstname’]) ? $_POST[‘firstname’] : null;
$lastname = !empty($_POST[‘lastname’]) ? $_POST[‘lastname’] : null;
$dob = !empty($_POST[‘dob’]) ? $_POST[‘dob’] : null;

if (!is_string($firstname)) {
throw new Exception (‘Invalid first name, it must be a string’);
}

if (!is_string($lastname)) {
throw new Exception (‘Invalid first name, it must be a string’);
}

if (empty($dob)) {
throw new Exception (‘No date of birth entered’);
}

$dateCheck = DateTime::createFromFormat(‘m/d/Y’,$dob);
if (!$dateCheck || $dateCheck->format(‘m/d/Y’) !== $dob) {
throw new Exception (‘Invalid date of birth, it should be in the following format: mm/dd/yyyy’);
}

/*
* Everything OK, include body.php here
* Remember to use htmlentities or similar to escape variables to avoid XSS
*/

} catch (Exception $e) {
/* The catch block should be at the very end of your script */
echo 'Error: ’ . $e->getMessage();
}

/* You shouldn’t end php files with ?> if you don’t have to. */[/php]

you can find available timezones here: http://php.net/manual/en/timezones.php

Sponsor our Newsletter | Privacy Policy | Terms of Service