public function validate_uniqueness(KohanaValidation $v, $field_name) { $sql = "SELECT COUNT(*) FROM {$this->table} WHERE {$field_name} = ?"; $vals = array($v[$field_name]); //if this is an UPDATE (as opposed to an INSERT), ignore this record's existing value if (!empty($v[$this->pkid])) { $sql .= " AND {$this->pkid} <> ?"; $vals[] = (int) $v[$this->pkid]; } $count = $this->db->GetOne($sql, $vals); if ($count) { $v->add_error($field_name, __FUNCTION__); } }
protected function add_standard_rules(KohanaValidation &$v, $fields_and_labels) { $cols = $this->db->MetaColumns($this->table); foreach ($cols as $col) { if (array_key_exists($col->name, $fields_and_labels)) { $field = $col->name; $label = $fields_and_labels[$field]; $type = $col->type; if ($col->not_null) { $v->add_rule($field, 'required', "{$label} is required."); } if ($type == 'varchar') { $v->add_rule($field, "length[0,{$col->max_length}]", "{$label} cannot exceed {$col->max_length} characters in length."); } if ($type == 'float') { $v->add_rule($field, 'numeric', "{$label} must be a number."); } if ($type == 'int') { $v->add_rule($field, 'digit', "{$label} must be a whole number."); if ($col->unsigned) { if ($col->not_null) { $v->add_rule($field, 'atleast[1]', "You must choose a {$label}."); //Assumes required unsigned ints are foreign key id's, and hence have a dropdown list for selections } else { $v->add_rule($field, 'atleast[0]', "{$label} must be a positive number"); } } } } } }