@madpilot makes

Update: Improved validation in CakePHP for version 1.x

I recently started a new project in CakePHP and thought it time to use version 1. But it seems the way that the validator code works has changed, so here is the updated code:

The following goes in app_model.php

Updated validator code
  1. function invalidFields ($data = array())
  2. {
  3. if (empty($data)) {
  4. $data = $this->data;
  5. }
  6. if (!$this->beforeValidate()) {
  7. return false;
  8. }
  9. if (!isset($this->validate)) {
  10. return true;
  11. }
  12. if (!empty($data)) {
  13. $data = $data;
  14. } elseif (isset($this->data)) {
  15. $data = $this->data;
  16. }
  17. if (isset($data[$this->name])) {
  18. $data = $data[$this->name];
  19. }
  20. $errors = array();
  21. foreach($this->validate as $field_name => $validators) {
  22. foreach($validators as $validator) {
  23. if (isset($data[$field_name]) && !preg_match($validator[‘expression’], $data[$field_name])) {
  24. $errors[$field_name] = $validator[‘message’];
  25. }
  26. }
  27. }
  28. $this->validationErrors = $errors;
  29. return $errors;
  30. }

The validation helper method (See my previous post) looks like this:

  1. function tagErrorMessages() {
  2. $messages = “”;
  3. if(isset($this->validationErrors)) {
  4. foreach($this->validationErrors as $tag) {
  5. foreach($tag as $element => $message) {
  6. $messages .= sprintf(SHORT_ERROR_MESSAGE, empty($message) ? ‘Error in field: ‘ . $element : $message);
  7. }
  8. }
  9. }
  10. return $messages;
  11. }

Leave a comment