Controller validation in Cakephp - cakephp

I wish to validate in controller in cakephp. Though my validations are working well in Models but instead of model I wish to validate it in controller as well.
What I did to validate in contrller.
$validates = array('email' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A email is required'
),
'isUnique' => array(
'rule' => array('notEmpty'),
'message' => 'This email is already registered'
),
'email' => array(
'rule' => array('email'),
'message' => 'Enter valid mail address'
)
));
if ($this->User->validates($validates)) {
die("Action can be performed as validated !! Fields are correct");
} else {
die("Action can't be performed !! Fields are in-correct");
}
It always end me in correct condition no matters if field is correct or not. Please help

Setting $this->Model->validates = $validates; will work for you as suggested in the previous answer but you risk overwriting all other validation rules which may be set in the Model. It's much better to add, modify and remove validation rules on the fly like such:
$this->Model->validator()
->add('email', 'required', array(
'rule' => array('notEmpty'),
'message' => 'A email is required'
))
->add('email', 'isUnique', array(
'rule' => array('notEmpty'),
'message' => 'This email is already registered'
))
->add('email', 'email', array(
'rule' => array('email'),
'message' => 'Enter valid mail address'
));
I left your array exactly as you presented it, however I assume you have the wrong rule on isUnique
You can read more about binding rules here: http://book.cakephp.org/2.0/en/models/data-validation.html#dynamically-change-validation-rules

Try this -
$data = $this->request->data;
$this->ModelName->set($data);
if ($this->ModelName->validates()) {
// it validated logic
} else {
// didn't validate logic
$errors = $this->ModelName->validationErrors;
}
Suppose you want to validate a particular field in cakephp Controller, then for that below code will be use -
$this->ModelName->validationErrors['html_field_name'][] = 'Your Error Message goes here';

Edit your code:
$this->$Model->validate = array('email' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A email is required'
),
'isUnique' => array(
'rule' => array('notEmpty'),
'message' => 'This email is already registered'
),
'email' => array(
'rule' => array('email'),
'message' => 'Enter valid mail address'
)
));
It work with me :)

Related

Cakephp isUnique is not working properly

isUnique validation doesn't work if there there is validation error only of uniqueness in user creating form and gives error of 'The page isn't redirecting properly'.
Model code is:
class User extends AppModel {
public $validate = array(
'username' => array(
'notEmpty' => array(
'rule' => array('email'),
'message' => 'Please supply a valid email address.'
),
'isUnique' => array(
'rule' => 'isUnique',
'message' => 'This email has already been taken.'
)
),
'password' => array(
'min' => array(
'rule' => array('minLength', 3),
'message' => 'Password must be at least 3 characters.'
),
'required' => array(
'rule' => 'notEmpty',
'message' => 'Please enter a password.'
),
),
'cpassword' => array(
'required' => 'notEmpty',
'match' => array(
'rule' => 'validatePasswdConfirm',
'message' => 'Passwords do not match'
)
)
);
}
When I enter mismatch passwords then it gives error of 'Passwords do not match' and also gives error 'This email has already been taken.' if a username is already there in users table but the problem is when I Only enter the username which already exists and enter a match password then it goes to a page with error "The page isn't redirecting properly".
How can I fix this issue?
Thanks in advance.
if you have used $this->Auth->login() in beforeFilter for any condition, remove it and use !empty($this->Auth->user('id')) instead of $this->Auth->login() for you conditions in beforeFilter.

How users can sign up with null values in cakephp?

some users can resgister with null values in my cakephp website !!
when i try to register with null value im getting the error messages of my model, but someone do that, i found 8 users with no data (no usernam, no email, no names... !!!!! )
this is my signup (add) action:
if($this->request->is('Post')){
$this->User->create();
$this->request->data['User']['user_id'] = $this->Auth->User('id');
if($this->User->save($this->request->data)){
$iduser=$id=$this->User->getLastInsertId();
$this->Session->setFlash(_('your accoutn has been created, check you inbox.'));
$this->redirect(array('action'=>'login',$iduser));
}
else
$this->Session->setFlash(_('Erreur !'));
}
$this->set('title_for_layout','users sign up');
and this is a part of my users model :
public $validate =array(
'username' => array(
'length' => array(
'rule' => array('minLength', 5),
'message' => 'error !',
'required' => true,
),
'alphanum' => array(
'rule' => 'alphanumeric',
'message' => 'error !',
),
'unique' => array(
'rule' => 'isUnique',
'message' => 'error !)',
),
),
'password' => array(
'length' => array(
'rule' => array('minLength', 6),
'message' => 'error !',
'required' => true,
'on' => 'create'
),
'alphanum' => array(
'rule' => 'alphanumeric',
'message' => 'error !',
'on' => 'create'
),
),
'email' => array(
'email' => array(
'rule' => 'email',
'message' => 'error !',
),
'unique' => array(
'rule' => 'isUnique',
'message' => 'error !',
),
),
(other fields are checked too)
so, how someone can signup with no data ??????!
please help !
Are the creating the accounts and then removing the data thereafter?
Is there the facility for the user to edit these details out later on?
You need to specify which fields are empty and post the full validation from the controller.

Attribute required = false in special cases

I have a User model with a lot of attributes and validation rules:
class User extends AppModel {
public $hasMany = 'Serviceorder';
public $validate = array(
'name' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A name is required'
)
),
...
'password' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A password is required'
)
),
...
);
}
This makes sense to me because when creating a user a password is always required.
In some cases, like when editing a user, I don't want the password to be required. When there's no new password, the password is not changed. How can I do that?
change the password validation as below :-
'password' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A password is required',
'on' => 'create'
)
),

cakephp login form validation on blank username and password

I have checked cakephp validation for a long time to validate my login form. My problem is when i enter username and password as blank the validation not showing.
Login function in UserController.php contains
if ($this->request->is('post')) {
$this->user->set($this->request->data);
$errors = $this->user->invalidFields();
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirect());
} else {
$this->Session->setFlash($this->Auth->authError, 'default', array(), 'auth');
$this->redirect($this->Auth->loginAction);
}
} else {
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirect());
}
}
My User.php Model contains validator as
public $validate = array(
'username' => array(
'isUnique' => array(
'rule' => 'isUnique',
'message' => 'The username has already been taken.',
),
'notEmpty' => array(
'rule' => 'notEmpty',
'message' => 'This field cannot be left blank.',
),
),
'email' => array(
'email' => array(
'rule' => 'email',
'message' => 'Please provide a valid email address.',
),
'isUnique' => array(
'rule' => 'isUnique',
'message' => 'Email address already in use.',
),
),
'password' => array(
'rule' => array('minLength', 6),
'message' => 'Passwords must be at least 6 characters long.',
),
'current_password' => array(
'rule' => '_identical',
),
'name' => array(
'rule' => 'notEmpty',
'message' => 'This field cannot be left blank.',
),
);
Actually my login form contains only usgername and password. But i have set this validation for userregistration form. The validation worked correctly in registration form but in the case of login the validation not working. Yes io know there is lot of questions posted on this website itself regarding the same issue, but nothing solve my problem, i have tried all the stackoverflow questions. Please Help
Validation only occurs when saving, or when you directly call the validation method using:
$this->Model->validates();
You aren't getting validation errors because you aren't actually validating your data. To get validation errors showing you'll need to do the following:
if ($this->request->is('post')) {
$this->User->set($this->request->data);
if ($this->User->validates()) {
echo "This is valid!";
} else {
echo "This is invalid";
$errors = $this->User->validationErrors;
}
}

cakephp Custom validation rule message

I have a custom validation rule to check if two passwords entered are the same, and if they arent I wish to have a message that says "Passwords do not match".
The rule works, however, when the passwords don't match it simply displays the normal error message, what's going on?
var $validate=array(
'passwd2' => array('rule' => 'alphanumeric',
'rule' => 'confirmPassword',
'required' => true,
'allowEmpty'=>false));
function confirmPassword($data)
{
$valid = false;
if ( Security::hash(Configure::read('Security.salt') .$data['passwd2']) == $this->data['User']['passwd'])
{
$valid = true;
$this->invalidate('passwd2', 'Passwords do not match');
}
return $valid;
}
It says "This field cannot be left blank"
EDIT:
The strange thing is, if I leave one of the password fields blank, both error messages say "This field cannot be left blank"
However, if I put something in both, then it correctly says "Passwords do not match"
I think you made it too complex. Here is how I do it:
// In the model
public $validate = array(
'password' => array(
'minLength' => array(
'rule' => array('minLength', '8')
),
'notEmpty' => array(
'rule' => 'notEmpty',
'required' => true
)
),
'confirm_password' => array(
'minLength' => array(
'rule' => array('minLength', '8'),
'required' => true
),
'notEmpty' => array(
'rule' => 'notEmpty'
),
'comparePasswords' => array(
'rule' => 'comparePasswords' // Protected function below
),
)
);
protected function comparePasswords($field = null){
return (Security::hash($field['confirm_password'], null, true) === $this->data['User']['password']);
}
// In the view
echo $form->input('confirm_password', array(
'label' => __('Password', true),
'type' => 'password',
'error' => array(
'comparePasswords' => __('Typed passwords did not match.', true),
'minLength' => __('The password should be at least 8 characters long.', true),
'notEmpty' => __('The password must not be empty.', true)
)
));
echo $form->input('password', array(
'label' => __('Repeat Password', true)
));
You should use the 'message' key in your $validate array to specify the message:
'message' => 'Your passwords do not match'
Further reading: http://book.cakephp.org/view/1143/Data-Validation
And then you can access the fields and the messages by $this->modelName->invalidFields(), which will return you the fields that didn't pass the validation and the message that you have setted for them...
In the controller I mean...
http://book.cakephp.org/view/1182/Validating-Data-from-the-Controller

Resources