Created
November 5, 2010 02:21
-
-
Save benubois/663550 to your computer and use it in GitHub Desktop.
Validator: PHP Form 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 | |
/** | |
* Validate | |
*/ | |
class Validator | |
{ | |
/** | |
* form validation rules and options | |
* | |
* @var array | |
**/ | |
public $options = array(); | |
/** | |
* whether or not the form has been submitted | |
* | |
* @var bool | |
**/ | |
public $has_post_data = FALSE; | |
/** | |
* container for values that have passed validation | |
* | |
* @var array | |
**/ | |
public $clean = array(); | |
/** | |
* container for form error messages | |
* | |
* @var array | |
**/ | |
public $errors = array(); | |
function __construct() | |
{ | |
// Has the form been submitted? | |
$this->has_post_data = ('POST' == $_SERVER['REQUEST_METHOD']) ? TRUE : FALSE; | |
} | |
/** | |
* check all post data to see if any of the data needs to be validated | |
* | |
* @param array|$options array of rules and messages for the form | |
* @return void | |
**/ | |
public function validate($options) | |
{ | |
$this->options = $options; | |
if ($this->has_post_data) | |
{ | |
foreach ($this->options['rules'] as $name => $value) | |
{ | |
// Get rules for the field | |
$this->apply_rules($name); | |
} | |
} | |
} | |
/** | |
* process validation rules for an individual field. set errors and add to $this->clean | |
* | |
* @param string|$name the name of the field to validate | |
* @return $this | |
**/ | |
protected function apply_rules($name) | |
{ | |
// Assume field is valid | |
$field_valid = TRUE; | |
$value = $_POST[$name]; | |
if (array_key_exists($name, $this->options['rules'])) | |
{ | |
foreach ($this->options['rules'][$name] as $method => $args) | |
{ | |
if (method_exists(__CLASS__, $method) || is_callable($method)) | |
{ | |
if (method_exists(__CLASS__, $method)) | |
{ | |
$valid = $this->$method($args, $value); | |
} | |
elseif (is_callable($method)) | |
{ | |
$valid = $method($value); | |
} | |
if (FALSE === $valid) | |
{ | |
// Set error message | |
$this->errors[$name] = $this->options['messages'][$name][$method]; | |
// Mark field as invalid | |
$field_valid = TRUE; | |
// stop processing rules | |
break; | |
} | |
} | |
else | |
{ | |
throw new Exception('Unknown validation rule: ' . $method); | |
} | |
} | |
} | |
// If the field is still valid add it to the clean array | |
if (TRUE === $field_valid) | |
{ | |
$this->clean[$name] = $value; | |
} | |
return $this; | |
} | |
/** | |
* html encode field value | |
* | |
* @param string|$name the name of the field to html encode | |
* @return $string | |
**/ | |
public function html($name) | |
{ | |
if (isset($_POST[$name])) | |
{ | |
return htmlentities($_POST[$name], ENT_QUOTES, 'UTF-8'); | |
} | |
else | |
{ | |
return ''; | |
} | |
} | |
/** | |
* get error message for a field | |
* | |
* @param string|$name the name of the field to html encode | |
* @return $string | |
**/ | |
public function get_error($name, $id = '') | |
{ | |
$id = (empty($id)) ? $name : $id; | |
if (isset($this->errors[$name])) | |
{ | |
return '<label for="' . $id . '" class="error">' . $this->errors[$name] . '</label>'; | |
} | |
else | |
{ | |
return ''; | |
} | |
} | |
/** | |
* get classes for a field | |
* | |
* @param string|$name the name of the field | |
* @return $string | |
**/ | |
public function get_classes($name) | |
{ | |
$classes = array(); | |
if (isset($this->errors[$name])) | |
{ | |
$classes[] = 'error'; | |
} | |
return implode(' ', $classes); | |
} | |
/** | |
* is the form valid | |
* | |
* @return $bool TRUE if the form is valid, FALSE if not | |
**/ | |
public function form_valid() | |
{ | |
return ($this->has_post_data && FALSE === $this->has_errors()) ? TRUE : FALSE; | |
} | |
/** | |
* whether or not the form has errors | |
* | |
* @return $bool TRUE if the form has errors, FALSE if not | |
**/ | |
public function has_errors() | |
{ | |
return (count($this->errors) > 0) ? TRUE : FALSE; | |
} | |
/** | |
* required, the field must contain a value | |
* | |
* @param mixed|$args arguments to determine if the field is required | |
* @return bool true if it passes validation false if it fails | |
**/ | |
protected function required($args, $value) | |
{ | |
return ('' == $value) ? FALSE : TRUE; | |
} | |
/** | |
* minlength, the minimum length a field can be | |
* | |
* @param mixed|$args arguments to determine if the field is required | |
* @return bool true if it passes validation false if it fails | |
**/ | |
protected function minlength($length, $value) | |
{ | |
return (strlen($value) < $length) ? FALSE : TRUE; | |
} | |
/** | |
* maxlength, the maximum length a field can be | |
* | |
* @param integer|$length the maximum lenght the field should be | |
* @return bool true if it passes validation false if it fails | |
**/ | |
protected function maxlength($length, $value) | |
{ | |
return (strlen($value) > $length) ? FALSE : TRUE; | |
} | |
/** | |
* rangelength, must be between two values | |
* | |
* @param array|$range the two integer values the field should be between | |
* @return bool true if it passes validation false if it fails | |
**/ | |
protected function rangelength($range, $value) | |
{ | |
return ($this->minlength($range[0], $value) && $this->maxlength($range[1], $value)) ? TRUE : FALSE; | |
} | |
/** | |
* length, must be exactly the specified length | |
* | |
* @param integer|$length how long the field should be | |
* @return bool true if it passes validation false if it fails | |
**/ | |
protected function length($length, $value) | |
{ | |
return (strlen($value) == $length) ? TRUE : FALSE; | |
} | |
/** | |
* equalto, must be equal to the specified field | |
* | |
* @param string|$name the name of the field the field must be equal to | |
* @return bool true if it passes validation false if it fails | |
**/ | |
protected function equalto($name, $value) | |
{ | |
return ($_POST[$name] == $value) ? TRUE : FALSE; | |
} | |
/** | |
* email, the field must be a valid email address | |
* | |
* @param mixed|$args arguments to determine if the field is required | |
* @return bool true if it passes validation false if it fails | |
**/ | |
public function email($args, $email) | |
{ | |
// from http://dev.kohanaframework.org/projects/kohana2/repository/entry/trunk/system/helpers/valid.php#L59 | |
return (bool) preg_match('/^[-_a-z0-9\'+*$^&%=~!?{}]++(?:\.[-_a-z0-9\'+*$^&%=~!?{}]+)*+@(?:(?![-.])[-a-z0-9.]+(?<![-.])\.[a-z]{2,6}|\d{1,3}(?:\.\d{1,3}){3})(?::\d++)?$/iD', (string) $email); | |
} | |
/** | |
* number, the field must be a number | |
* | |
* @param string value to check | |
* @return bool true if it passes validation false if it fails | |
**/ | |
public function number($args, $value) | |
{ | |
return (bool) preg_match('/^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/', $value); | |
} | |
/** | |
* digits, the field must only contain digits | |
* | |
* @param string value to check | |
* @return bool true if it passes validation false if it fails | |
**/ | |
public function digits($args, $value) | |
{ | |
return (bool) preg_match('/^\d+$/', (string) $value); | |
} | |
} | |
function custom($test) | |
{ | |
return TRUE; | |
} | |
$validator = new Validator; | |
$validator->validate(array( | |
'rules' => array( | |
'first_name' => array( | |
'required' => TRUE, | |
'digits' => TRUE, | |
'custom' => custom(), | |
), | |
), | |
'messages' => array( | |
'first_name' => array( | |
'required' => 'First name is a required field', | |
'digits' => 'First name must be digits', | |
), | |
), | |
)); | |
function custom($value='') | |
{ | |
# code... | |
} | |
if ($validator->form_valid()) | |
{ | |
print 'form valid'; | |
} | |
?> | |
<form action="<?php print $_SERVER['PHP_SELF']; ?>" method="post" accept-charset="utf-8"> | |
<label for="first_name">First Name</label> | |
<input id="first_name" type="text" name="first_name" value="<?php print $validator->html('first_name'); ?>" class="text <?php print $validator->get_classes('first_name'); ?>" /> | |
<?php print $validator->get_error('first_name'); ?> | |
<p><input type="submit" value="Continue →"/></p> | |
</form> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment