Commit 64b5873e authored by Nigel McNie's avatar Nigel McNie Committed by Nigel McNie
Browse files

Implement custom form rules. Set $values[$key] even if it wasn't posted, so

people don't have to do silly isset() checks when using rules.
parent 005ecac8
...@@ -331,9 +331,12 @@ class Form { ...@@ -331,9 +331,12 @@ class Form {
} }
$global = ($this->method == 'get') ? $_GET : $_POST; $global = ($this->method == 'get') ? $_GET : $_POST;
foreach ($global as $key => $value) { foreach ($elementnames as $name) {
if (in_array($key, $elementnames)) { if (isset($global[$name])) {
$result[$key] = $value; $result[$name] = $global[$name];
}
else {
$result[$name] = null;
} }
} }
return $result; return $result;
...@@ -345,21 +348,21 @@ class Form { ...@@ -345,21 +348,21 @@ class Form {
*/ */
private function validate($values) { private function validate($values) {
foreach ($this->get_elements() as $element) { foreach ($this->get_elements() as $element) {
if (!empty($element['rules']['required']) && (!isset($values[$element['name']]) || $values[$element['name']] == '')) { if (isset($element['rules']) && is_array($element['rules'])) {
$this->set_error($element['name'], get_string('This field is required', 'mahara')); foreach ($element['rules'] as $rule => $data) {
} if (!$this->get_error($element['name'])) {
if (!empty($element['rules']['minlength'])) { // Get the rule
$minlength = intval($element['rules']['minlength']); $function = 'form_rule_' . $rule;
if (!isset($values[$element['name']]) || strlen($values[$element['name']]) < $minlength) { if (!function_exists($function)) {
$this->set_error($element['name'], get_string('You must put a minimum of ' @include_once('form/rules/' . $rule . '.php');
. $minlength . ' characters in this field')); if (!function_exists($function)) {
} throw new FormException('No such form rule "' . $rule . '"');
} }
if (!empty($element['rules']['maxlength'])) { }
$maxlength = intval($element['rules']['maxlength']); if ($error = $function($values[$element['name']], $data)) {
if (!isset($values[$element['name']]) || strlen($values[$element['name']]) > $maxlength) { $this->set_error($element['name'], $error);
$this->set_error($element['name'], get_string('You must put a maximum of ' }
. $maxlength . ' characters in this field')); }
} }
} }
} }
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment