CakePhp: read View rule message inside controller - php

I've declared my validation fields of my view in this way:
public $validate = array(
'myField' => array(
'alphaNumeric' => array(
'rule' => 'alphaNumeric',
'required' => true,
'message' => 'username required'
),
'unique' => array(
'rule' => 'isUnique',
'required' => 'create',
'message' => 'Username already used'
)
)
);
Is there a way to know (inside the relative controller class) when this message is fired?
Because if one of these rules is violated, I would like to perform some tasks, and not simply show message to the user.

Yes, first set the data to the model in your controller:
$this->ModelName->set($this->request->data);
Then, to check if the data validates, use the validates method of the model, which will return true if it validates and false if it doesn’t:
if ($this->ModelName->validates()) {
// it validated logic
} else {
// didn't validate logic
$errors = $this->ModelName->validationErrors;
}
To know more about validationErrors, go to cakephp Validating Data from the Controller article.

Related

CakePHP show custom validation message on empty fields

I'm searching a way to show custom message declared on validation array inside a notEmpty rule.
So if i have this validation:
'username' => array(
'notEmpty' => array(
'rule' => 'notEmpty',
'message' => 'username empty',
'required' => true
),
//other validation rules
if i leave e filed empty into form, cake php show his own default message for empty field, and not my custom message. How can i show it and catch this event into my Controller class?
The key to the array should be the fieldname, unless I'm misunderstanding your context:
'myFieldName' => array(
'rule' => 'notEmpty',
'message' => 'custom message for empty field',
'required' => true
)
If I've misunderstood the context, please edit your question giving a little bigger picture of the validation code in your model.

CakePHP how to validate if isNull multiple fields

I have the following database model.
Model1 hasMany Users
Model2 hasMany Users
Model3 hasMany Users
And one user can only belong to one Model. So the table user fields are the following:
id username password model1_id model2_id model3_id
I need to check in CakePHP User model that the three foreign keys cannot be NULL at the same time.
Which is the best way to solve that? Because I can't create any custom validation rules, validation rules was thought for validating one field. So How can I validate multiple fields and print the pertinent validation error.
you should add this in your Model.
public $validate = array(
'fieldName1' => array(
'rule' => 'ruleName',
'required' => true,
'allowEmpty' => false,
'message' => 'Your Error Message'
)
);
Cakephp Validation links
Use Custom validations
public $validate = array(
'table1_id' => array(
'rule' => array('custom_validation'),
'required' => true,
'allowEmpty' => false,
'message' => 'Your Error Message'
),
'table2_id' => array(
'rule' => array('custom_validation'),
'required' => true,
'allowEmpty' => false,
'message' => 'Your Error Message'
),
'table2_id' => array(
'rule' => array('custom_validation'),
'required' => true,
'allowEmpty' => false,
'message' => 'Your Error Message'
)
);
function custom_validation(){
if( empty($this->data['table1_id']) && empty($this->data['table2_id']) && empty($this->data['table3_id']) ) {
return false;
}
return true;
}

Field isn't validated in right way in CakePHP

I was trying to set up form validation inside CakePHP. Model is recognized when entering submit form, but i have few problems:
When i enter any validation rule, the only thing that is checked is whenever in field is any text.
I can't do multiple rules per field - they are not working.
I can still type in artist field values, that are not alphanumeric...
Here is my Model code:
class Sounds extends AppModel {
public $validate = array(
'artist' => array(
'rule1' => array(
'rule' => 'notEmpty',
'message' => 'Please enter value',
'last' => false
),
'rule2' => array(
'rule' => 'alphaNumeric',
'message' => 'Please enter alphanumeric value'
)
)
);
Also in SoundController i have code, to check if form was validated:
if ($this->Sounds->validates()) { //action if validated } else {
$errors = $this->Sounds->validationErrors;
$this->set('errors_submit',$errors);

Getting validation on login form in CakePHP 2.2

I have built a simple CakePHP app with a users login system and have hooked up the Cake Form plugin by Milesj.me (not sure if that's causing the problems).
However my validation seems to have applied itself to the login form as well as the signup form. So when I try and login, I am getting errors like 'Username already in use'.
Any ideas what would cause this? Has something changed in CakePHP that adds the validation to authentication forms as well?
Also why am I having to hash the password in the model? I was under the impression that CakePHP hashed passwords automatically? And I've not needed to do it before. However If I don't do it, then it was saving the password in the DB as in and not hashed...
Here is my view, controller and model:
<?php echo $this->Form->create(); ?>
<?php echo $this->Form->input('User.username',
array('tabindex'=>1, 'autofocus',
'label'=>array('class'=>'placeholder','text'=>'Username'))); ?>
<?php echo $this->Form->input('User.password',
array('tabindex'=>2, 'type'=>'password',
'label'=>array('class'=>'placeholder','text' =>'Password' ))); ?>
<div class="input button">
<button class="orangeButton" tabindex="3" type="submit"><span class="icon login">Log in</span></button>
</div>
<?php echo $this->Form->end(); ?>
controller:
public function login() {
if ($this->request->data) {
$this->User->set($this->request->data);
if ($this->User->validates() && $this->Auth->login()) {
if ($user = $this->Auth->user()) {
$this->User->Profile->login($user['id']);
$this->Session->delete('Forum');
$this->redirect($this->referer());
}
}
}
}
Note: the calls to Profile model for login just saves some data for when last logged in and other stuff and doesn't actually do anything regarding authentication!
and the model:
class User extends AppModel {
public $name = 'User';
public $hasOne = array(
'Profile' => array('className' => 'Forum.Profile')
);
public $hasMany = array(
'Access' => array('className' => 'Forum.Access'),
'Moderator' => array('className' => 'Forum.Moderator')
);
public $validate = array(
'email' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A valid email address is required'
),
'email' => array(
'rule' => array('email'),
'message' => 'This is not a valid email address'
),
'unique' => array(
'rule' => array('isUnique'),
'message' => 'This email is already in use'
)
),
'username' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A username is required'
),
'unique' => array(
'rule' => array('isUnique'),
'message' => 'This username is already in use'
),
'alphaNumeric' => array(
'rule' => array('alphaNumeric'),
'message' => 'Usernames must only contain letters and numbers'
),
'between' => array(
'rule' => array('between', 4, 20),
'message' => 'Usernames must be between 4 and 20 characters long'
)
),
'password' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A password is required'
)
)
);
public function beforeSave()
{
if (isset($this->data[$this->alias]['password']))
{
$this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
}
return true;
}
Just add to your validation rules 'on' => 'create'
http://book.cakephp.org/2.0/en/models/data-validation.html#on
As per cakephp
In case of multiple rules per field by default if a particular rule
fails error message for that rule is returned and the following rules
for that field are not processed.
But if first rule doesn't fail, then it continue to evaluate second
rule.
You can remove particular validation by following way
$this->validator()->remove('username', 'unique');

Unique username and email with CakePHP Auth component

I'm new to Cake and building an application to learn it. I'm having a few troubles with my user registration system. So far this is my registration code in my Users controller:
public function register() {
$this->set('title_for_layout', 'Register');
if ($this->request->is('post')) {
$this->User->create();
if ($this->User->save($this->request->data)) {
$this->Session->setFlash('The user has been saved');
$this->redirect(array('action' => 'register'));
} else {
$this->Session->setFlash('The user could not be saved. Please, try again.');
}
}
}
And within my User model I have this method where I hash the passwords:
public function beforeSave() {
if (isset($this->data[$this->alias]['password'])) {
$this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
}
return true;
}
This works, the user is added to my users table in my database with their username, email and hashed password. However, there are no checks done to make sure the username and email are unique.
From my limited understanding, I would need to add some validation rules to my User model to make sure the username and email fields are unique before they're entered into the table? At the moment I just have these validation rules:
public $validate = array(
'username' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A username is required'
)
),
'email' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'An email is required'
)
),
'password' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A password is required'
)
)
);
Also, my registration form has a Password (confirm) field called passwordConf. I would like to check if the user entered his passwords correctly before they're entered into the users table, but I'm not sure how to do that. I'm guessing that somewhere in my register method I need to check if the two passwords are the same.
Thanks for any help.
The isUnique rule will work with your username and email fields. Here is a sample of code that shows how to use multiple rules per field:
public $validate = array(
'username' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'You must enter a username.'
),
'length' => array(
'rule' => array('between', 3, 15),
'message' => 'Your username must be between 3 and 15 characters long.'
),
'unique' => array(
'rule' => 'isUnique',
'message' => 'This username has already been taken.'
)
),
'password' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'You must enter a password.'
),
'length' => array(
'rule' => array('minLength', '6'),
'message' => 'Your password must be at least 6 characters long.'
)
),
'email' => array(
'email' => array(
'rule' => array('email'),
'message' => 'Please enter a valid email address.'
)
)
);
As for comparing the passwords just edit your beforeSave callback and check the passwords against each other, returning true if they match and false if they do not. Something like this:
public function beforeSave() {
if (isset($this->data[$this->alias]['password'])) {
if($this->data[$this->alias]['password'] === $this->data[$this->alias]['passwordConf']) {
$this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
return true;
} else {
return false;
}
}
return true;
}
CakePHP actually has a validation rule called isUnique, which you can use to check the username and e-mail. A list of built in rules can be found here. You can use this and the Data Validation Tutorial to check the user name and e-mail. As to checking if the passwords are the same, you MAY be able to use the EqualTo rule shown in the rules list, assuming you can make your validation rules on the fly every request.

Categories