/** * Validates the model, returning a reusable Validator object in the process. * * Example (using callbacks): * <code> * Validator::validate(array( * 'model' => $_POST, * 'rules' => array(...), * 'validHandler' => function() { * // Model validated. * }, * 'invalidHandler' => function() { * // Model failed validation. * }, * )); * </code> * * Example (using methods): * <code> * $validator = Validator::validate(array( * 'model' => $_POST, * 'rules' => array(...), * )); * if ($validator->model()) { * // Model validated. * } else { * // Model failed validation. * } * </code> * * Possible options include: * * - <b>model</b> (required) The model to validate. * - <b>rules</b> (required) The rules the model is validated against. * - <b>validHandler</b> A callable that gets called if the model is valid. * - <b>invalidHandler</b> A callable that gets called if the model fails validation. * * @param array $options An array of options. * @return Validator An reusable Validator instance. */ public static function validate($options) { $noop = function () { }; $valid_handler = $options['validHandler'] ?: $noop; $invalid_handler = $options['invalidHandler'] ?: $noop; $validator = new Validator($options['model'], $options['rules']); if ($validator->model()) { $valid_handler($validator); } else { $invalid_handler($validator); } return $validator; }
<?php require 'vendor/autoload.php'; use Cdmckay\Pajama\Validator; $rules = array('first_name' => 'required', 'last_name' => 'required', 'password_1' => array('required' => true, 'minlength' => 5, 'equalTo' => '#password_2'), 'password_2' => array('required' => true, 'minlength' => 5, 'equalTo' => '#password_1')); $successful = null; Validator::validate(array('model' => $_POST, 'rules' => $rules, 'validHandler' => function () use(&$successful) { $successful = 1; }, 'invalidHandler' => function () use(&$successful) { $successful = 0; })); header('Location: form.php?successful=' . ($successful ? 1 : 0));
<?php require 'vendor/autoload.php'; use Cdmckay\Pajama\Validator; use Cdmckay\Pajama\ValidatorContext; Validator::addMethod('regex', function (ValidatorContext $context, $value, $param) { return $context->optional($value) || preg_match('/' . $param . '/', $value); }); $rules = json_decode(file_get_contents(__DIR__ . '/rules.json'), true); $response = array(); Validator::validate(array('model' => $_POST, 'rules' => $rules, 'validHandler' => function () use(&$response) { $response['successful'] = true; }, 'invalidHandler' => function (Validator $validator) use(&$response) { $response['successful'] = false; $response['invalid_field_names'] = array_keys($validator->invalidFields()); })); header('Content-Type: application/json'); echo json_encode($response);