Skip to content

Instantly share code, notes, and snippets.

@xeoncross
Created May 22, 2012 21:08
Show Gist options
  • Save xeoncross/2771633 to your computer and use it in GitHub Desktop.
Save xeoncross/2771633 to your computer and use it in GitHub Desktop.
Validator Class
<?php
$validator = new Validator();
// Each validation rule is a property of the validator object.
$validator->username = function($value, $key, $self)
{
if(preg_match('~\W~', $value))
{
return 'Your username must only contain letters and numbers';
}
}
$validator->password = function($value, $key, $self)
{
if(strlen($value) < 8)
{
return 'Your password must be at least 8 characters long';
}
};
// $_POST = array('username' => ..., 'password' => ...)
if( ! $validator($_POST))
{
// Return a JSON object with the validation errors (great for jQuery)
die(json_encode($validator->errors()));
}
else
{
// Save new user to database
}
<?php
/**
* Validator class based on anonymous functions.
*
* @see http://php.net/manual/en/functions.anonymous.php
*/
class Validator
{
public $errors;
/**
* Validate the given array of data using the functions set
*
* @param array $data to validate
* @return array
*/
public function __invoke(array $data)
{
unset($this->errors);
$errors = array();
foreach((array) $this as $key => $function)
{
$value = NULL;
if(isset($data[$key]))
{
$value = $data[$key];
}
$error = $function($value, $key, $this);
if($error)
{
$errors[$key] = $error;
}
}
$this->errors = $errors;
return ! $errors;
}
/**
* Return the validator errors
*
* @return array
*/
public function errors()
{
return $this->errors;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment