A class for validating array models, typically the $_POST
or $_GET
superglobals.
addMethod(string $method_name, callable $method)
Example:
Validator::addMethod('alphanumeric', function(ValidatorContext $context, $value) {
return $context->optional($value) || ctype_alnum($value);
});
string
The name of the method, i.e. 'range' or 'creditcard'.
callable
The validation method, typically an anonymous function.
field(string $name) : bool
This is the rough equivalent of the 'element' method in the jQuery Validation plugin.
Example:
$validator = Validator::validate(array(...));
if ($validator->field('first_name')) {
// The 'first_name' field is valid.
}
string
The name of the field to validate.
bool
True if valid, false otherwise.getMethods() : array
array
The array containing all the validation methods.getModel() : array
array
The flattened model.getRules() : array
array
The normalized rules.invalidFields() : array
Example:
$validator = Validator::validate(array(...));
foreach ($validator->invalidFields() as $name => $value) {
error_log($name . ' did not validate.');
}
array
An associative array of all invalid fields.model() : bool
This is the rough equivalent of the 'form' method in the jQuery Validation plugin.
Example:
$validator = Validator::validate(array(...));
if ($validator->model()) {
// Model validated.
}
bool
True if the model is valid, false otherwise.numberOfInvalidFields() : int
Example:
$validator = Validator::validate(array(...));
error_log($validator->numberOfInvalidFields() . ' failed validation.');
int
The number of fields that failed validation.validate(array $options) : \Pajama\Validator
Example (using callbacks):
Validator::validate(array(
'model' => $_POST,
'rules' => array(...),
'validHandler' => function() {
// Model validated.
},
'invalidHandler' => function() {
// Model failed validation.
},
));
Example (using methods):
$validator = Validator::validate(array(
'model' => $_POST,
'rules' => array(...),
));
if ($validator->model()) {
// Model validated.
} else {
// Model failed validation.
}
Possible options include:
array
An array of options.
\Pajama\Validator
An reusable Validator instance.__construct(array $model, array $rules)
array
The model to validate.
array
The rules the model is validated against.
flatten(array $model) : array
For example, $a['foo']['bar'] = 'baz'
becomes $a['foo[bar]'] = 'baz'
.
array
array
normalizeRule(array | string $value) : array
array
string
array
normalizeRules(array $rules) : array
array
array
$methods : array
$model : array
$rules : array