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'
)
),
Related
Below is my model function which is already working...
i need to validate name field.
when i submit blank form.....the form display Enter portfolio name.
and when i enter numeric value in name field the form display Enter valid portfolio name.
but when i submit the blank form the form does not display any message for name field.
and when i enter the numeric value in name textbox and submit then it display message properly.
please help me to make both the rule working for name field.
so plz suggest me how to implement this.
<?php
class Portfolio extends AppModel{
var $name = 'Portfolio';
var $validate = array(
'name' => array(
'rule' => 'notEmpty',
'message' => "Enter portfolio name."
),
'name' => array(
'rule' => '/^[a-zA-Z]*$/',
'message' => "Enter valid portfolio name."
),
'job_title' => array(
'rule' => 'notEmpty',
'message' => "Enter your quote request."
),
'freight_mode'=> array(
'rule'=>'notEmpty',
'message'=>"Enter your frieght mode."
),
'expected_transport_growth' => array(
'rule' => 'notEmpty',
'message' => "Select expected transport growth."
),
'current_annual_spend' => array(
'rule' => 'notEmpty',
'message' => "Select current annual spend."
),
'expected_annual_spend' => array(
'rule' => 'notEmpty',
'message' => "Select expected annual spend."
),
'quotes_expiry' => array(
'rule' => 'notEmpty',
'message' => "Enter deadline on quote request."
),
'quotes_required' => array(
'rule' => 'notEmpty',
'message' => "Select quote requrest required."
),
'contract_start_date' => array(
'rule' => 'notEmpty',
'message' => "Enter contract start date."
),
);
/*var $belongsTo = array(
'SupplierUquotes' => array(
'className' => 'SupplierUquotes',
'foreignKey' => 'id'
),);*/
}
?>
Try this
<?php
public $validate = array(
'name' => array(
'notEmpty' => array(
'rule' => 'notEmpty',
'message' => "Enter portfolio name."
),
'valid' => array(
'rule' => '/^[a-zA-Z]*$/',
'message' => "Enter valid portfolio name."
)
)
);
?>
Try this code:
<?php
class Portfolio extends AppModel{
var $name = 'Portfolio';
var $validate = array(
'name' => array( // here 'name' is the field name to be validated
'notEmpty'=>array( // here 'notEmpty' is user defined rule name, it should not be "rule" which is a cakephp reserved word, I think
'rule'=>'notEmpty', // here 'notEmpty' is the actual rule applied on the field 'name'
'message'=>'Enter portfolio name.'
),
'validName'=>array( // here 'validName' is another user-defined rule name. It should be different for a particular field.
'rule'=>'/^[a-zA-Z]*$/',
'message'=>'Enter valid portfolio name.'
)
),
'job_title' => array(
'rule' => 'notEmpty',
'message' => "Enter your quote request."
),
'freight_mode'=> array(
'rule'=>'notEmpty',
'message'=>"Enter your frieght mode."
),
'expected_transport_growth' => array(
'rule' => 'notEmpty',
'message' => "Select expected transport growth."
),
'current_annual_spend' => array(
'rule' => 'notEmpty',
'message' => "Select current annual spend."
),
'expected_annual_spend' => array(
'rule' => 'notEmpty',
'message' => "Select expected annual spend."
),
'quotes_expiry' => array(
'rule' => 'notEmpty',
'message' => "Enter deadline on quote request."
),
'quotes_required' => array(
'rule' => 'notEmpty',
'message' => "Select quote requrest required."
),
'contract_start_date' => array(
'rule' => 'notEmpty',
'message' => "Enter contract start date."
),
);
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.
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 :)
I have added the following validation to my User model:
class User extends AppModel
{
var $useTable = 'users';
var $validate = array(
'username' => array(
'rule'=>array('minLength', 1),
'message'=>'Please enter your username' ),
'password' => array(
'rule'=>array('minLength', 1),
'message'=>'Please enter your password' )
);
}
The idea is that if a user doesn't fill out the fields on the login form then it will show the messages above. However it doesn't work???
What you should actually use is the 'notEmpty', set 'allowEmpty' to false and ensure it is 'required'
var $validate = array(
'username' => array(
'rule' => 'notEmpty',
'required' => true,
'allowEmpty' => false,
'message' => 'Please enter a username'
)
'password' => array(
'rule' => 'notEmpty',
'required' => true,
'allowEmpty' => false,
'message' => 'Please enter a password'
)
);
Update:
Bit of a hack, but change the name of your login form to 'UserLogin' - then in your before filter check if $this->data['UserLogin'] is set. If it is - check if $this->data['UserLogin']['username'] is empty, if so just set a flash saying its empty. Same goes for password.
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