6
votes

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.)...

4

4 Answers

6
votes

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'.

0
votes

You didn't point out which framework you're using (doesn't look like CodeIgniter). However, if $this->User->validationErrors['email'] returns a simple text string there's not much you can do with it.

Does the user object have any other properties? Might be a good idea to print_r it to see what's inside.

0
votes

It has Cakephp tags on the post. Don't validate data from controller, always try to do this in models and push this through to controllers and viewers instead...

0
votes

well, invalidFields() include both the fields and the error messages. You can guess the rule by the error message, right?

Edit: it can be done this way:

$this->User->validationErrors['email'] == $this->User->validate['email']['unique']['message']