Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use only certain validation set for validating data in Cake PHP?

I was trying to validate my User model data and I came upon this problem.

Say i have the following validation rules, stored in $validate variable:

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

In the UsersController controller, I have two actions: register() and login(). The problem is, how do I validate the username field in the register() action using ONLY the usernameCheckForRegister rule, and how do I validate the username field in the login() action, using the other rule, usernameCheckForLogin? Is there any behaviour or method in CakePHP which allows me to choose which set of rules to apply to a form field when validating?

Thank you in advance for your help!

like image 460
linkyndy Avatar asked Aug 28 '10 21:08

linkyndy


1 Answers

I think I ran over the 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 behaviour implies defining several "general" rules under which you define all your field-related rules.

So, instead of doing:

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

you do:

/**
 * 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 toggle between validation sets like this:$this->User->setValidation('register');

Even though you have to write a little bit more code, I think this solution best fits my needs

like image 183
linkyndy Avatar answered Oct 13 '22 10:10

linkyndy