Search code examples
phpvalidationyiiyii-validation

Yii model rules() method doesn't work


Hi have a problem with the rules() method of one of my application model.

Here is rules():

public function rules() 
{ 
  $newRules = array(
    array('password_verification', 'required'),
    array('password_verification', 'length', 'min'=>6, 'max'=>32),
    array('password', 'compare', 'compareAttribute'=>'password_verification'),
    array('username, email', 'length', 'min'=>3,'max'=>255),
    array('password', 'length','min'=>6, 'max'=>32),
    array('username, email', 'unique'),
    array('email', 'email'),
    array('valid_until_formated','compare', 
          'compareAttribute'=>'valid_from_formated','operator'=>'>'),
    array('id, type,username, password, password_verification, email, valid_from, valid_until, valid_until_formated, valid_from_formated, added_on, created_by','safe'),
  );
}

(sorry for the format of the code).

And here is the problem:

I want to test if "valid_until_formated" is greater than "valid_from_formated".

When I submit my form with wrong values (valid_from greater than vali_ until) I get an error message, I can see it on firebug but the values are inserted in data base.

But for instance if I try with a username already used or a password with fewer character than 6 then I have an error and nothing is created in database?

Does anybody have an idea why this rule doesn't work (even if I get an error message) ? (this is the format of valid_until_formated, for example: "20121118" )

Thanks for reading me and sorry for my approximate English.

Have a good day :)

Michaël


Solution

  • Thanks you all for your answer.

    Actually it was a dump mistake I did.

    I didn't know the validate() method was call by the save() one. Actually I was trying to save a User and I didn't understand why the rules in my CustomUser model were not run -_-.

    The test was on my User:rules() and my CustomUser::rules() inherits my User::rules()...Anyway I fixed this issue like that.

    if(myCustomUser->validate()){

    myUser = new User;

    ... ...

    myUser->save(false);

    }

    Like that I can create a user with the validation rules of my CustomUser.

    Thanks, Have a nice day :)