Created
March 5, 2014 10:44
-
-
Save MadaraUchiha/9364984 to your computer and use it in GitHub Desktop.
Form object for validation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
Form { | |
private $vars = []; | |
private $validators = []; | |
private $errors = []; | |
private $validatedVars = []; | |
/** | |
* @param array $varArray Could be either the POST or the GET array | |
*/ | |
public function __construct(array $varArray) { | |
$this->vars = $varArray; | |
} | |
/** | |
* @param string $name The name of GET/POST parameter under test | |
* @param callable $validator The function that tests whether or not that field is valid or not | |
* Should take one parameter (the value of the field) and return TRUE/FALSE | |
* based on whether the input was valid or not. | |
* @param string $error Error string that would be displayed to the user in the case of a test failure. | |
*/ | |
public function bindValidator($name, callable $validator, $error) { | |
$this->validators[$name][] = ["validator" => $validator, "error" => $error]; | |
} | |
/** | |
* @return array Array of valid form elements. | |
*/ | |
public function validateForm() { | |
foreach ($this->validators as $name => $validators) { | |
$fieldValid = true; | |
foreach ($validators as $validator) { | |
$validatorPassed = $validator["validator"]($this->vars[$name]); | |
if (!$validatorPassed) { | |
$this->errors[] = $validator["error"]; | |
} | |
$fieldValid = $fieldValid && $validatorPassed; | |
} | |
if ($fieldValid) { | |
$this->validatedVars[$name] = $this->vars[$name]; | |
} | |
} | |
return $this->validatedVars; | |
} | |
public function getErrors() { | |
return $this->errors; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment