1
votes

I have some validation in my User model that checks the email address is unique, email address is formatted as an email etc.

For the login form in particular, I do want to validate that the email field is filled out with a proper email address BUT I do not want to fire the unique rule. I tried adding 'on' => 'create' to the unique rule but all the validation still fires.

This is what I have in my model:

public $validate = array (
'email' => array(
'email' => array(
        'rule' => 'email',
        'required' => 'create',
        'allowEmpty' => 'false'
    ),
'isUnique' => array(
            'rule' => 'isUnique',
            'on' => 'create',
            'message' => 'This email address already exists in the     database. Would you like to login?'
      )
);

And this is in the controller's login function:

if ($this->User->validates(array('fieldList' => array('email', 'password')))) {
    // do login, redirect etc.
}

This is my view

<?php echo $this->Form->create('User'); ?>
<fieldset>
    <legend><?php echo __('Please enter your email address and password'); ?></legend>
    <?php 
        echo $this->Form->input('email');
        echo $this->Form->input('password');
    ?>
</fieldset>
<?php echo $this->Form->end(__('Login')); ?>

How do I get cakePHP to recognize that certain validation rules should not fire for certain actions without having to "unset" rules.

And if I do wind up having to unset a rule, would I have to set it again to get it to fire where it should be firing or is the unset only good for the duration of the action?

Thanks!

1

1 Answers

0
votes

Method 1:

Just remove the validation isUnique for email before validating the data.

These are the possible ways to remove the validation by doing unset of the validation array keys.

$this->User->validator()->remove('email', 'isUnique');

(OR)

$validator = $this->User->validator();
unset($validator['email']['isUnique']);

And then validate the data here.

if ($this->User->validates(array('fieldList' => array('email', 'password')))) {
    // do login, redirect etc.
}

For more info you can check here to remove the validation.

Method 2:

you can also do the validation as like below.

just create one function in User model to validate the login form like this

User Model

public function loginValidate() {
    $validate1 = array (
        'email' => array(
            'rule' => 'email',
            'message' => 'please enter email.'
        ),
        'password' => array(
            'rule' => 'notEmpty',
            'message' => 'please enter password.'
        )
    );

    $this->validate = $validate1;
    return $this->validates();
}

Users Controller

public function login() {
   if ($this->User->loginValidate()) {
      // do login, redirect etc.
   }
}

I hope this helps you.