valitron
valitron copied to clipboard
Default values for non-required fields
Still working on the client-side interface, but in the meantime I've come up with something that others might find useful. Basically, the purpose is to allow default values for non-required fields. So, if a $_GET
or $_POST
array is passed into valitron, it can be easily updated with default values for missing parameters.
Extra function in valitron:
public function setDefault($field, $defaultValue) {
if (!isset($this->_fields[$field])){
$this->_fields[$field] = $defaultValue;
}
return true;
}
Usage:
// Sanitize input data
$get = filter_input_array(INPUT_GET, FILTER_SANITIZE_SPECIAL_CHARS);
// Initialize validation
$v = new Valitron\Validator($get);
// Required fields
$v->rule('required', 'box_id');
// Optional fields with default values
$v->setDefault('title', 'Cool Dude');
$v->setDefault('limit', null);
// Validate!
$v->validate();
// Handle errors
if (count($v->errors()) > 0)
exit();
// Update input array with any new default values
$get = $v->data();