Find out (in the controller) which specific validation rule failed

I have a user registration form with an email field that acts as a username and must be unique in the application.

User model has the following 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 this was a 'unique' rule that failed (to display various form elements, such as the "Send password to reset password" button).

I can check if the email field was valid or not ( if (isset($this->User->validationErrors['email'])) ), but how can I check the failure of a certain rule ?

Finding a specific error message like if ($this->User->validationErrors['email'] == "Already exists") simply wrong (l10n, etc.) ...

+6
source share
4 answers

Read http://book.cakephp.org/2.0/en/models/data-validation/validating-data-from-the-controller.html

Essentially you just need 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 this letter is, and if it is unique, we want the following rules in the model:

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

Before "returning a lie" to each of them, we need to establish somewhere that this verification rule failed. The easiest way: we can break the MVC convention and use the configuration class ( http://book.cakephp.org/view/924/The-Configuration-Class ) and install 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 log into it from the controller via:

 Configure::read('UserValidationFail'); 

This will give you either "email" or "isUnique".

+6
source

You did not specify which structure you are using (not like CodeIgniter). However, if $ this-> User-> validationErrors ['email'] returns a simple text string, you cannot do it.

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

0
source

There are Cakephp tags on this post. Do not check data from the controller, always try to do it in models and then use it for controllers and viewers ...

0
source

Well, invalidFields () includes both fields and error messages. You can guess the rule with the error message, right?

Edit: this can be done as follows:

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

Source: https://habr.com/ru/post/892846/


All Articles