I am trying to figure this out. I have som data which is entered using HTML_Quickform. I want to validate it, and it is easy with just adding rules.
However, I also need to validate the data just before it is saved - as I add some new values, and want to make sure that they are present. Now I can make another validation routine, but it would be somewhat smarter if the two validation routines had a knowledge of each other.
Anyone else have been struggling with this problem? Just a short example to show what I mean:
php Code:
Original
- php Code |
|
|
|
$form = new HTML_QuickForm;
$form->addElement('text', 'text', 'text');
$form->addRule('text', 'cannot be empty', 'required');
if ($form->isSubmitted() AND $form->validate()) {
$data = $form->exportValues();
$data['perm_user_id'] = $auth->getProperty('perm_user_id');
$ship = new Ship($db, $form->exportValues('id'));
// either in the save method or before, I want
// to make sure that perm_user_id is filled in
if ($ship->save()) {
header('Location: ship_edit.php');
}
}
I was thinking to have the Ship class implement an interface:
php Code:
Original
- php Code |
|
|
|
interface Validate {
function addRule();
}
interface Rule {
function isValid();
}
class NotEmptyRule implements Rule {
private $field;
private $value;
function __construct($field) {
}
function isValid($value) {
if (empty($value)) return false;
else return true;
}
}
And then do something the lines of:
php Code:
Original
- php Code |
|
|
|
class Ship implements Validate {
private
$rules =
array();
function addRule($field, $rule) {
$this->rules[$field][] = $rule;
}
function validate($fields) {
foreach ($this->rules[$key] AS $rule) {
if (!$rule->isValid($key[])) {
$this->error[$key] = $rule->error_msg;
}
}
}
if (count($this->
error) >
0) { return false;
}
}
function save($fields) {
if (!$this->validate()) return false;
}
}
But that is quite a lot of code to put in every class, if I have more classes - and I can't quite think of how I can couple it to the HTML_QuickForm rules? But perhaps it is necessary to make two different validation systems?