Yii Rules And Mandatory Properties

Hi guys!

I have a small issue of which I’m not certain how to resolve regarding validation rules, integrity and security.

I’m talking about ActiveRecord here.

I’m sure you’ve encountered an object which always had properties ( database fields ) which are mandatory and in every case, they should exist. Let’s say “username” property for a User object.

Let’s say you have User object with username property ( which is used for registration/login purposes ) and basically “username” property uniquely defines your user.

Now, imagine someone doing something like:




This shouldn’t be possible in any scenario.

So the logical way would be to edit the rules() method and add



If I do that, I’m opening username property to massive assignment and thus I create a security hole.

So what should I do?

How can I enforce "username" to be required without opening it to massive assignment?

I was thinking - maybe to explicitly define it as "unsafe" for all defined scenarios.

Or maybe in beforeValidate() do something…

How do you handle stuff like that?

if you want ‘username’ to be excluded from massive assignements just add another validator ‘unsafe’:



Ok, and then I can explicitly define it as "safe" for a specific scenario.

This is ok for me, thank you redguy!

in current Yii version (1.1.13) you can specify ‘except’ parameter:


array('username','unsafe', 'except'=>'create'),

I am not sure in which version this option was introduced…