Click To Launch Showreel

php validation class

Download
View

This is a PHP Validation class containing a number of methods for common validation operations I use. This class was built to save time, hopefully it will you too.

The class can be downloaded from the download link above. The view link takes you to a pastie page with the code printed on it (pastie uses a far better code rendering engine than I do).

Method List

  • between - checks that a value falls between two other values.
  • varEmpty - checks to ensure that a variable contains data.
  • email - validates a string to ensure that it matches proper email address format.
  • equal - checks two strings to ensure they are equal.
  • num - ensures a value is completely numeric and holds only numbers.
  • requiredFields - compares an array of values against an array of keys ensuring that each value that has a key that matches a value of the keys array holds a value.
  • arrayData - checks that an array has at least one value.
  • alphaNum - ensures a string is alphanumeric.
  • creditCardNo - ensures that a string matches a credit card format (16 digits, numbers only).
  • creditCardStart - validates a credit card start date (mm/yy) to ensure that it is in the past.
  • creditCardExpire - validates a credit card expiry date (mm/yy) to ensure that it is in the future.
  • pastDate - checks that a given date (yyyy-mm-dd format) is in the past.
  • futureDate - checks that a given date (yyyy-mm-dd format) is in the future.
  • dateBetween - checks that a given date falls between two dates.
  • validateFile - checks an uploaded file is smaller than 10MB, is pdf, doc, docx, xls or xlsx format (although you can quite easily change the mime types to match your needs).

When using the class, returning null will equate to a passed validation, returning false will equate to a failed validation.

Implementiation

						<?php
						require_once('validate.class.php');
						
						$v = new Validate();
						
						if($v->num(10) == null) {
							// validation passed. do something
						} else {
							// validation failed, do something else
						}
						?>
					

validate.class.php

						<?php
						/**
						 * Validation class
						 * Contains a number of validation methods to keep validation to one class
						 * When using, (i.e. varEmpty), you would need to check for the return being null to pass validation, i.e.
						 * if($validate->varEmpty($var, 'key name') == null):
						 * // validation passed. do something.
						 * else:
						 * // do something else
						 * endif;
						 * @author Pete Robinson - www.pete-robinson.co.uk
						 */

						class Validate
						{

							public $errors = array();

							/**
							 * Check that a numeric value falls between two other numberic values
							 * @param $min - int - the minimum value that $value must be
							 * @param $max - int - the maximum value that $value must be
							 * @param $value - the value to be checked
							 * @param $key - str - the variable name to be presented to the user in error report
							 */
							public function between($min, $max, $value, $key='')
							{
								if($value < $min || $value > $max) {
									$this->errors[] = $key . ' must be between ' . $min . ' and ' . $max . '.';
									return false;
								}
							}


							/**
							 * Check to see if a variable holds data
							 * @param $value - the variable to be validated
							 * @param $key - str - the variable name to be presented to the user in error report
							 */
							public function varEmpty($value, $key='')
							{
								if(!$value || $value == '' || empty($value)) {
									$this->errors[] = $key . ' must have a value.';
									return false;
								}
							}


							/**
							 * Check that an email address follows a valid email address format
							 * @param $value - str - the email address to be validated
							 * @param $key - str - the variable name to be presented to the user in error report
							 */
							public function email($value, $key='')
							{
								if(!preg_match('/^[A-Z0-9._-]+@[A-Z0-9][A-Z0-9.-]{0,61}[A-Z0-9]\.[A-Z.]{2,6}$/i', $value)) {
									$this->errors[] = $key . ' must be a valid e-mail address.';
									return false;
								}
							}


							/**
							 * Compare two values
							 * @param $value1 - str - the first value
							 * @param $value2 - str - the second value. Must match $value1 to pass validation
							 * @param $key1 - str - the variable name to be presented to the user in error report
							 * @param $key2 - str - the variable name to be presented to the user in error report
							 */
							public function equal($value1, $value2, $key1='', $key2='')
							{
								if($value1 != $value2) {
									$this->errors[] = $key1 . ' must be equal to ' . $key2 . '.';
									return false;
								}
							}


							/**
							 * Check whether a value is numeric
							 * @param $value - the number to be validated
							 * @param $key - str - the variable name to be presented to the user in error report
							 */
							public function num($value, $key='')
							{
								if(!ereg('^[[:digit:]]+$', $value)) {
									if($key) {
										$this->errors[] = $key . ' must be a numeric value.';
									}
									return false;
								}
							}



							/**
							 * Compare a list of required fields against an array
							 * @param $required - arr - the array of keys
							 * @param $fields - arr - the array of values
							 */
							public function requiredFields($required, $fields)
							{
								$results = array();
								$i = 0;
								foreach($required as $req) {
									if($this->varEmpty($fields[$req], $req) === false) {
										$results[$i] = $req;
										$i++;
									}
								}

								if($results) {
									return false;
								}
							}


							/**
							 * Check to see if an array holds one or more keys
							 * @param $arr - arr - the array to be validated
							 * @param $key - str - the variable name to be presented to the user in error report
							 */
							public function arrayData($arr, $key='')
							{
								if(count($arr) == 0 || !is_array($arr)) {
									$this->errors[] = $key . ' must be an array.';
									return false;
								}
							}


							/**
							 * Check to see if a value is alphanumeric
							 * @param $value - str - the value to be validated
							 * @param $key - str - the variable name to be presented to the user in error report
							 */
							public function alphaNum($value, $key='')
							{
								if(!preg_match('/^[a-zA-Z0-9]+$/', $value)) {
									$this->errors[] = $key . ' must be an alpha-numeric value.';
									return false;
								}
							}


							/**
							 * Check whether a given value is a valid credit card number.
							 * @param $number - int - the 16 digit credit card number
							 * @param $key - str - the variable name to be presented to the user in error report
							 */
							public function creditCardNo($number, $key='')
							{
								if(strlen($number) != 16) {
									$this->errors[] = $key . ' is not a valid credit card number.';
									return false;
								} else {
									if($this->num($number) === false) {
										$this->errors[] = $key . ' is not a valid credit card number.';
										return false;
									}
								}
							}


							/**
							 * Check to ensure that a credit card start date is in the past
							 * @param $month - int - the 2 digit month to be validated (i.e. 02)
							 * @param $year - int - the 2 digit year to be validated (i.e. 09)
							 * @param $key - str - the variable name to be presented to the user in error report
							 */
							public function creditCardStart($month, $year, $key='')
							{
								if($this->num($month) == null && $this->num($year) == null) {
									if($this->pastDate(($year+2000) . '-' . $month . '-01') === false) {
										$this->errors[] = $key . ' must be in the past.';
										return false;
									}
								} else {
									$this->errors[] = 'Month and year must be in numeric format.';
									return false;
								}
							}


							/**
							 * Check to ensure that a credit card expiry date is in the future
							 * @param $month - int - the 2 digit month to be validated (i.e. 02)
							 * @param $year - int - the 2 digit year to be validated (i.e. 09)
							 * @param $key - str - the variable name to be presented to the user in error report
							 */
							public function creditCardExpire($month, $year, $key='')
							{
								if($this->num($month) == null && $this->num($year) == null) {
									if($this->futureDate(($year + 2000) . '-' . $month . '-' . cal_days_in_month(CAL_GREGORIAN, $month, ($year + 2000))) === false) {
										$this->errors[] = $key . ' must be a date in the future.';
										return false;
									}
								} else {
									$this->errors[] = 'Month and year must be in numeric format';
									return false;
								}
							}


							/**
							 * Ensure a date (in Y-m-d format) is in the past
							 * @param $value - str - the date to be checked
							 * @param $key - str - the variable name to be presented to the user in error report
							 */
							public function pastDate($value, $key='')
							{
								if($value > date('Y-m-d')) {
									if($key) {
										$this->errors[] = $key . ' must be a date in the past.';
									}
									return false;
								}
							}


							/**
							 * Ensure that a date (Y-m-d format) is in the future
							 * @param $value - str - the date to be validated
							 * @param $key - str - the variable name to be presented to the user in error report
							 */
							public function futureDate($value, $key='')
							{
								if($value < date('Y-m-d')) {
									if($key) {
										$this->errors[] = $key . ' must be in the past.';
									}
									return false;
								}
							}


							/**
							 * Check that a date falls between two other dates
							 * @param $date - str - the subject of the method
							 * @param $from - str - the lower limit of the date range
							 * @param $to - str - the upper limit of the date range
							 * @param $key - str - the variable name to be presented to the user in error report
							 */
							public function dateBetween($date, $from, $to, $key='')
							{
								if(($date < $from) || ($date > $to)) {
									if($key) {
										$this->errors[] = $key . ' must be between ' . $from . ' and ' . $to . '.';
									}
									return false;
								}
							}


							/**
							 * Check that a file is in a valid document format (PDF, DOC, DOCX, XSL, XLSX)
							 * And that is has a max size of 10MB and has no errors
							 * Add your own mime types to the array if needed
							 * @param $file - arr - the $_FILES array of the file
							 */
							public function validateFile($file)
							{
								if($file['size'] >= 102400000) {
									$this->errors[] = 'File must be smaller than 10MB';
									return false;
								}

								if(!in_array($file['type'], array('application/pdf', 'application/msword', 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'))) {
									$this->errors[] = 'File must be in pdf, doc, xls, docx or xlsx format.';
									return false;
								}

								if($file['error'] > 0) {
									$this->errors[] = 'Error in uploaded file.';
									return false;
								}
							}



						}



						?>
					

YouTube

Ok, I bought a Peavey 6505 head about a month ago and was completely blown away by it's tone ever since. This thing is amazing. Sorry for going on a bit with the sound demos but once I hear this thing I just can't stop playing!

Send me an e-back

What's an eback? It's like a callback, but without the call. Complete the form below to drop me an e-mail and I'll e-mail you back as soon as I can.



eback »

Bring Down IE6!