How to use only a specific validation set to validate data in Cake PHP?

I tried to check my user model details, and I ran into this problem.

Let's say I have the following validation rules stored in the $ validate variable:

var $validate=array( "username" => array( "usernameCheckForRegister" => array( "rule" => ..., "message" => ... ), "usernameCheckForLogin" => array( "rule" => ..., "message" => ... ) ), //rules for other fields ); 

In the UserController, I have two actions: register () and login (). The problem is how can I check the username in the register () action using ONLY the usernameCheckForRegister rule, and how can I check the username in the login () action using another rule, the CheckForLogin username? Is there any behavior or method in CakePHP that allows me to choose which set of rules to apply to the form field when validating?

Thank you in advance for your help!

+6
php validation cakephp
source share
3 answers

I think I ran over a solution that fits my needs.

http://bakery.cakephp.org/articles/view/multivalidatablebehavior-using-many-validation-rulesets-per-model

Instead of defining several rules for each field, this behavior implies defining several β€œgeneral” rules, according to which you define all your rules associated with the field.

So, instead of doing:

 var $validate=array( "username" => array( "usernameCheckForRegister" => array( "rule" => ..., "message" => ... ), "usernameCheckForLogin" => array( "rule" => ..., "message" => ... ) ), //rules for other fields ); 

:

 /** * Default validation ruleset */ var $validate = array( 'username' => /* rules */, 'password' => /* rules */, 'email' => /* rules */ ); /** * Custom validation rulesets */ var $validationSets = array( 'register' => array( 'username' => /* rules */, 'password' => /* rules */, 'email' => /* rules */, ), 'login' => array( 'username' => /* rules */, 'password' => /* rules */ ) ); 

And then in your controller, you switch between verification sets as follows: $this->User->setValidation('register');

Even if you need to write a little more code, I think this solution best suits my needs.

+8
source share

Check out the manual :

 var $validate=array( "username" => array( "usernameCheckForRegister" => array( "rule" => ..., "message" => ..., "on" => "create" ), "usernameCheckForLogin" => array( "rule" => ..., "message" => ..., "on" => "update" ) ), //rules for other fields ); 

UPDATE: Oh ... I just noticed that it is not possible to use the validation rule when logging in unless you update the user every time you try to log in. You can change login () to confirm the username.

0
source share

A bit awkward solution, but I just turned off the ones that I do not use in the controller. It may be messy, but for a simple login / signup it does the trick.

 unset($this->User->validate['username']['usernameCheckForRegister']); 
0
source share

All Articles