The validation class gives you access to advanced form validation. You get the option to require fields, check for minimum and maximum lengths, look for numbers, and even valid email addresses.

The validation class needs to be instantiated.
$validation = new Validate();

Let’s take a look at some code that does the following things for someone trying to update their username: (Note: The existing username was pre-populated in the form, so we’re looking for this to be DIFFERENT than what was pre-populated).


//Don't forget to instantiate
$validation = new Validate();

//Checks to see if what's in the field is different than the pre-populated value
if ($userdetails->username != $_POST['username']){

//If it is, grab it with the Input class
      $displayname = Input::get("username");

//What fields are you wanting to check?
      $fields=array('username'=>$displayname);

//Let's make an array of what you want to check
      $validation->check($_POST,array(
        'username' => array(
//The 'display' is required because it helps fill in the error messages.  
         'display' => 'Username',

//Is this field required?
          'required' => true,

//Does it need to be unique and if so to what table and what column?
          'unique_update' => 'users,'.$userId,

//The minimum length-  Not really necessary because it's required so it can't be zero
          'min' => 1,

//The maximum length
          'max' => 25
        )
      ));
    if($validation->passed()){

//If the validation passed do your database query
      $db->update('users',$userId,$fields);

//Give a positive response if you want. 
      echo "Username Updated";
    }

//Wherever you want your errors to display, just put this div (in HTML)
display_errors();?>

Validate.php

If you copy and paste this code, please get rid of the spaces or @ symbols before the opening php tag.


<@?php
class Validate{
	private $_passed = false,
			$_errors = array(),
			$_db = null;

	public function __construct(){
		$this->_db = DB::getInstance();
	}

	public function check($source, $items = array()){
		foreach ($items as $item => $rules) {
			$item = sanitize($item);
			$display = $rules['display'];
			foreach ($rules as $rule => $rule_value) {
				$value = trim($source[$item]);
				$value = sanitize($value);

				if ($rule === 'required' && empty($value)) {
					$this->addError(["{$display} is required",$item]);
				} else if(!empty($value)){
					switch ($rule) {
						case 'min':
							if (strlen($value) < $rule_value) {
								$this->addError(["{$display} must be a minimum of {$rule_value} characters.",$item]);
							}
							break;

						case 'max':
							if (strlen($value) > $rule_value) {
								$this->addError(["{$display} must be a maximum of {$rule_value} characters.",$item]);
							}
							break;

						case 'matches':
							if ($value != $source[$rule_value]) {
								$match = $items[$rule_value]['display'];
								$this->addError(["{$match} and {$display} must match.",$item]);
							}
							break;

						case 'unique':
							$check = $this->_db->get($rule_value, array($item, '=', $value));
							if ($check->count()) {
								$this->addError(["{$display} already exists. Please choose another {$display}.",$item]);
							}
							break;

						case 'unique_update':
							$t = explode(',', $rule_value);
							$table = $t[0];
							$id = $t[1];
							$query = "SELECT * FROM {$table} WHERE id != {$id} AND {$item} = '{$value}'";
							$check = $this->_db->query($query);
							if ($check->count()) {
								$this->addError(["{$display} already exists. Please choose another {$display}.",$item]);
							}
							break;

						case 'is_numeric':
							if (!is_numeric($value)) {
								$this->addError(["{$display} has to be a number. Please use a numeric value.",$item]);
							}
							break;

							case 'valid_email':
								if(!filter_var($value,FILTER_VALIDATE_EMAIL)){
									$this->addError(["{$display} must be a valid email address.",$item]);
								}
							break;
					}
				}
			}

		}

		if (empty($this->_errors)) {
			$this->_passed = true;
		}
		return $this;
	}

	private function addError($error){
		$this->_errors[] = $error;
	}

	public function errors(){
		return $this->_errors;
	}

	public function passed(){
		return $this->_passed;
	}

	public function display_errors(){
		$html = '
    '; foreach($this->_errors as $error){ if(is_array($error)){ $html .= '
  • '.$error[0].'
  • '; $html .= ''; }else{ $html .= '
  • '.$error.'
  • '; } } $html .= '
'; return $html; } }