Skip to content

Instantly share code, notes, and snippets.

@itzikbenh
Last active Jul 31, 2017
Embed
What would you like to do?
WordPress simple validator class. Still in the work
<?php if( isset( $_SESSION['errors'] ) ): ?>
<div class="alert alert-danger">
<a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
<ul>
<?php foreach ($_SESSION["errors"] as $error): ?>
<li><?php echo $error; ?></li>
<?php endforeach ?>
</ul>
</div>
<?php endif; ?>

Currently it only supports required, sometimes and date_format validation rules.

You need to pass the $_POST data, the validation rules and optionally custom error messages. If there's any error it will automatically redirect the user back to the form and preset the errors.

(new Validator($_POST, [
  'pr_title'       => 'required',
  'pr_description' => 'required',
  'company_name'   => 'required',
  'pr_date'        => 'required|date|date_format:m/d/Y',
], [
  'pr_title.required'       => 'The title field is required.',
  'pr_description.required' => 'The content field is required.',
  'pr_date.required'        => 'The date field is required.',
  'pr_date.date_format'     => 'The date field does not match the format mm/dd/yyyy.',
]))->pass_or_fail();
<?php
class Validator {
private $data;
private $rules;
private $messages;
private $errors = [];
public function __construct($data, array $rules, array $messages = []) {
$this->data = $data;
$this->rules = $rules;
$this->messages = $messages;
}
public function pass_or_fail() {
foreach ($this->rules as $attribute => $rules) {
$this->validate_attribute($attribute, $rules);
}
if ( count( $this->errors ) ) {
$_SESSION["errors"] = $this->errors;
$_SESSION['old'] = $_POST;
wp_safe_redirect( wp_get_referer() );
exit;
}
}
public function validate_attribute($attribute, $rules) {
$rules = explode('|', $rules);
$required = in_array( 'required', $rules );
$sometimes = in_array( 'sometimes', $rules );
$filled = isset( $this->data[$attribute] ) && $this->data[$attribute];
if ( ( $required && ( ! $filled ) ) || ( ( ! $sometimes ) && ( ! $filled ) ) ) {
$this->errors[] = $this->messages["{$attribute}.required"] ?? "The ".str_replace('_', ' ', $attribute)." field is required.";
return;
}
if ( $sometimes && ( ! $filled ) ) {
return;
}
foreach ( $rules as $rule ) {
if ( $rule === 'email' && ! is_email( $this->data[$attribute] ) ) {
$this->errors[] = $this->messages["{$attribute}.email"] ?? "The ".str_replace('_', ' ', $attribute)." must be a valid email.";
break;
}
if ( $rule === 'date' && ! $this->valid_date( $this->data[$attribute] ) ) {
$this->errors[] = $this->messages["{$attribute}.date"] ?? "The ".str_replace('_', ' ', $attribute)." must be a valid date.";
break;
}
if ( strncmp($rule, 'date_format', strlen('date_format')) === 0 ) {
$format = str_replace( 'date_format:', '', $rule );
$value = $this->data[$attribute] ?? '';
if ( ! $this->valid_date_format( $value, $format ) ) {
$this->errors[] = $this->messages["{$attribute}.date_format"] ?? "The ".str_replace('_', ' ', $attribute)." does not match the format $format";
break;
}
}
}
}
protected function valid_date( $value ) {
if ( $value instanceof DateTime ) {
return true;
}
if ( ( ! is_string( $value ) && ! is_numeric( $value ) ) || strtotime( $value ) === false ) {
return false;
}
$date = date_parse( $value );
return checkdate( $date['month'], $date['day'], $date['year'] );
}
protected function valid_date_format( $value, $format ) {
if ( ! is_string( $value ) && ! is_numeric( $value ) ) {
return false;
}
$date = DateTime::createFromFormat($format, $value);
return $date && $date->format($format) == $value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment