Skip to content

Instantly share code, notes, and snippets.

@MadaraUchiha
Created March 5, 2014 10:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MadaraUchiha/9364984 to your computer and use it in GitHub Desktop.
Save MadaraUchiha/9364984 to your computer and use it in GitHub Desktop.
Form object for validation
<?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