public
Last active

Validator Class

  • Download Gist
index.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
<?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
}
validator.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
<?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;
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.