Adding Server-Side Date Validation - PHP and Jquery

Now that you have a basic understanding of regexes, you’re ready to start validating user input. For this app, you need to ensure that the date format is correct, so that the app doesn’t crash by attempting to parse a date that it can’t understand.

You’ll begin by adding server-side validation. This is more of a fallback because later you’ll addvalidation with jQuery. However, you should never rely solely on JavaScript to validate user inputbecause the user can easily turn off JavaScript support and therefore completely disable your JavaScript validation efforts.

Defining the Regex Pattern to Validate Dates

The first step toward implementing date validation is to define a regex pattern to match the desiredformat. The format the calendar app uses is YYYY-MM-DD HH:MM:SS.

Setting up Test Data

You need to modify regex.php with a valid date format and a few invalid formats, so you can test yourpattern. Start by matching zero or more numeric characters with your regex pattern. Do this by makingthe following changes shown in bold:

<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.wisdomjobs.com/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.wisdomjobs.com/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type"
content="text/html;charset=utf-8" />
<title>Regular Expression Demo</title>
<style type="text/css">
em {
background-color: #FF0;
border-top: 1px solid #000;
border-bottom: 1px solid #000;
}
</style>
</head>
<body>
<?php
/*
* Set up several test date strings to ensure validation is working
*/
$date[] = '2010-01-14 12:00:00';
$date[] = 'Saturday, May 14th at 7pm';
$date[] = '02/03/10 10:00pm';
$date[] = '2010-01-14 102:00:00';
/*
* Date validation pattern
*/
$pattern = "/(d*)/";
foreach ( $date as $d )
{
echo "<p>", preg_replace($pattern, "<em>$1</em>", $d), "</p>";
}
/*
* Output the pattern you just used
*/
echo "n<p>Pattern used: <strong>$pattern</strong></p>";
?>
</body>
</html>

After saving the preceding code, reload in your browser to see all numeric characters highlighted

Matching any numeric character

Matching any numeric character

Matching the Date Format

To match the date format, start by matching exactly four digits at the beginning of the string to validatethe year: /^(d{4})/

Validating the year section of the date string

Validating the year section of the date string

Next, you need to validate the month by matching the hyphen and two more digits: /^(d{4}(-d {2}))/

Expanding the validate month section of the date string

Expanding the validate month section of the date string

Notice that the month and date sections are identical: a hyphen followed by two digits. This meansyou can simply repeat the month-matching pattern to validate the day using a repetition operator afterthe group: /^(d{4}(-d{2}){2})/

Adding the day part of the date string to the pattern

Adding the day part of the date string to the pattern

Now match a single space and the hour section: /^(d{4}(-d{2}){2} (d{2}))/

Validating the hour section of the date string

Validating the hour section of the date string

To validate the minutes, you match a colon and exactly two digits: /^(d{4}(-d{2}){2}(d{2}) (:d{2}))/

Validating the minutes section of the date string

Validating the minutes section of the date string

Finally, repeat the pattern for the minutes to match the seconds, and then use the dollar signmodifier to match the end of the string: /^ (d {4} (-d {2} ) {2} (d {2} ) (:d {2} ) {2} ) $/

Validating the seconds section of the date string and completing the pattern

Validating the seconds section of the date string and completing the pattern

Armed with this regex pattern, you can now validate the date input in your application.

Adding a Validation Method to the Calendar Class

To validate the date string, you will add a new private method to the Calendar class called _validDate().This method will accept the date string to be validated, then compare it to the validation patternusing preg_match(), which returns the number of matches found in the given string. Because this particular pattern will only match if the entire string conforms to the pattern, a valid date will return 1,while an invalid date will return 0.

If the date is valid, the method will return TRUE; otherwise,it will return FALSE.

Add this method to the Calendar class by inserting the following bold code into class.calendar.inc.php:

<?php
class Calendar extends DB_Connect
{
private $_useDate;
private $_m;
private $_y;
private $_daysInMonth;
private $_startDay;
public function __construct($dbo=NULL, $useDate=NULL) {...}
public function buildCalendar() {...}
public function displayEvent($id) {...}
public function displayForm() {...}
public function processForm() {...}
public function confirmDelete($id) {...}
/**
* Validates a date string
*
* @param string $date the date string to validate
* @return bool TRUE on success, FALSE on failure
*/
private function _validDate($date)
{
/*
* Define a regex pattern to check the date format
*/
$pattern = '/^(d{4}(-d{2}){2} (d{2})(:d{2}){2})$/';
/*
* If a match is found, return TRUE. FALSE otherwise.
*/
returnpreg_match($pattern, $date)==1 ? TRUE : FALSE;
}
private function _loadEventData($id=NULL) {...}
private function _createEventObj() {...}
private function _loadEventById($id) {...}
private function _adminGeneralOptions() {...}
private function _adminEntryOptions($id) {...}
}
?>

Returning an Error if the Dates Don’t Validate

Your next step is to modify the processForm() method so it calls the _validDate() method on both the start and end times for new entries. If the validation fails, simply return an error message. Add the following bold code to processForm() to implement the validation:

<?php
class Calendar extends DB_Connect
{
private $_useDate;
private $_m;
private $_y;
private $_daysInMonth;
private $_startDay;
public function __construct($dbo=NULL, $useDate=NULL) {...}
public function buildCalendar() {...}
public function displayEvent($id) {...}
public function displayForm() {...}
/**
* Validates the form and saves/edits the event
*
* @return mixed TRUE on success, an error message on failure
*/
public function processForm()
{
/*
* Exit if the action isn't set properly
*/
if ( $_POST['action']!='event_edit' )
{
return "The method processForm was accessed incorrectly";
}
/*
* Escape data from the form
*/
$title = htmlentities($_POST['event_title'], ENT_QUOTES);
$desc = htmlentities($_POST['event_description'], ENT_QUOTES);
$start = htmlentities($_POST['event_start'], ENT_QUOTES);
$end = htmlentities($_POST['event_end'], ENT_QUOTES);
/*
* If the start or end dates aren't in a valid format, exit
* the script with an error
*/
if ( !$this->_validDate($start)
|| !$this->_validDate($end) )
{
return "Invalid date format! Use YYYY-MM-DD HH:MM:SS";
}
/*
* If no event ID passed, create a new event
*/
if ( empty($_POST['event_id']) )
{
$sql = "INSERT INTO `events`
(`event_title`, `event_desc`, `event_start`,
`event_end`)
VALUES
(:title, :description, :start, :end)";
}
/*
* Update the event if it's being edited
*/
Else
{
/*
* Cast the event ID as an integer for security
*/
$id = (int) $_POST['event_id'];
$sql = "UPDATE `events`
SET
`event_title`=:title,
`event_desc`=:description,
`event_start`=:start,
`event_end`=:end
WHERE `event_id`=$id";
}
/*
* Execute the create or edit query after binding the data
*/
try
{
$stmt = $this->db->prepare($sql);
$stmt->bindParam(":title", $title, PDO::PARAM_STR);
$stmt->bindParam(":description", $desc, PDO::PARAM_STR);
$stmt->bindParam(":start", $start, PDO::PARAM_STR);
$stmt->bindParam(":end", $end, PDO::PARAM_STR);
$stmt->execute();
$stmt->closeCursor();
/*
* Returns the ID of the event
*/
return $this->db->lastInsertId();
}
catch ( Exception $e )
{
return $e->getMessage();
}
}
public function confirmDelete($id) {...}
private function _validDate($date) {...}
private function _loadEventData($id=NULL) {...}
private function _createEventObj() {...}
private function _loadEventById($id) {...}
private function _adminGeneralOptions() {...}
private function _adminEntryOptions($id) {...}
}
?>

You can test the validation by entering a bad entry into the form.

An entry with bad date values that should fail validation

An entry with bad date values that should fail validation

After this form is submitted, the app will simply output the error message and die. The calendar application is designed for users with JavaScript enabled; you use this approach to prevent the app from displaying errors.

The error message displayed when invalid dates are supplied

The error message displayed when invalid dates are supplied

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

PHP and Jquery Topics