Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find out (in controller) which specific validation rule failed

I have a user registration form with email field which acts as username and should be unique accross the application.

User model has following are validation rules for this field:

var $validate = array(
    'email' => array(
        'email' => array('rule' => 'email', 'allowEmpty' => false, 'last' => true, 'message' => 'Valid email address required'),
        'unique' => array('rule'=> 'isUnique', 'message' => 'Already exists'),
    ),
);

In my controller I want to check if it was the 'unique' rule which has failed (to display a different form elements, like "Send password recovery email" button).

I can check whether email field was valid or not (if (isset($this->User->validationErrors['email']))), but how do I check for specific rule failure?

Looking for specific error message like if ($this->User->validationErrors['email'] == "Already exists") just doesn't seem right (l10n etc.)...

like image 426
lxa Avatar asked Jul 15 '11 16:07

lxa


1 Answers

Have a read of http://book.cakephp.org/2.0/en/models/data-validation/validating-data-from-the-controller.html

Essentially you just have to use:

$errors = $this->ModelName->invalidFields();

Which will give you an array of all validation errors.


Update (Custom Validation Rules):

So we want to check if it's an email, and if it's unique - we want the following rules in the model:

CakePHP Validation : http://book.cakephp.org/2.0/en/models/data-validation.html

Before the "return false" of each, we need to set somewhere that this validation rule failed. Easiest way: we can break the MVC convention, and use the configuration class (http://book.cakephp.org/view/924/The-Configuration-Class) and set it there, and access it accordingly in the controller.

Configure::write('UserValidationFail','email'); //for email before return false
Configure::write('UserValidationFail','isUnique'); //for unique before return false

And then access it from the controller via:

Configure::read('UserValidationFail');

Which will give you either 'email' or 'isUnique'.

like image 106
Shaz Amjad Avatar answered Sep 29 '22 11:09

Shaz Amjad