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.)...
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'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With