I am Trying to validate data from Form(.ctp file) in cakephp 2.3.8.
echo $this->Form->create('User').'<br />'.
$this->Form->input('handle', array(
'rule' => 'notEmpty',
'alphaNumeric' => array(
'rule' => 'alphaNumeric',
'required' => true,
'message' => 'Username must be only letters and numbers, no special characters'
),
'between' => array(
'rule' => array('between', 4, 8),
'message' => 'Username must be between 4 and 8 characters',
),
'isUnique' => array(
'rule' => 'isUnique',
'message' => 'This username is already taken. Please choose a different one.'
))).'<br />'.
$this->Form->input('email',array(
'type'=>'text',
'placeholder'=>'Enter your E-mail',
'class'=>'form-control')).'<br />'.
$this->Form->input('password',array(
'type'=>'password',
'placeholder'=>'Enter your password',
'class'=>'form-control'));?>
This is my modle code
public function beforeSave($options = array()) {
parent::beforeSave($options = array());
if (isset($this->data['User']['password'])) {
$this->data['User']['password'] = AuthComponent::password($this->data['User']['password']);
}
$this->data['User']['token'] = Security::hash(mt_rand(),'md5',true);
$this->data['User']['resetkey'] = Security::hash(mt_rand(),'md5',true);
return true;
}
but when i singup, it not validating data and i don't know where i am mistaking
I have not seen validation rules in the view before, only in either the model or the controller. This may very well be an alternate method. Try moving validation code to the model.
class User extends AppModel {
public $validate = array(
'handle' => array(
'lengthCheck'=>array(
'rule'=>array('between', 4, 8),
'message'=>'The username must be between 4 and 8 characters.'
),
'isUnique'=>array(
'rule'=>'isUnique',
'message'=>'This username is already taken. Please choose a different one.'
),
'alphanumeric' => array(
'rule' => array('alphanumeric'),
'message' => 'Username must be only letters and numbers, no special characters',
),
'notempty' => array(
'rule' => array('notempty'),
'message' => 'Please enter your username',
),
),
'password' => array(
'notempty' => array(
'rule' => array('notempty'),
'message' => 'Please enter your password',
),
),
'email' => array(
'email' => array(
'rule' => array('email'),
'message' => 'Invalid email',
),
'notempty' => array(
'rule' => array('notempty'),
'message' => 'Please enter your email',
),
),
);
In your view
<?php
echo $this->Form->create('User');
echo $this->Form->input('handle', array(
'placeholder'=>'Enter your username',
'class'=>'form-control'
));
echo $this->Form->input('email', array(
'placeholder'=>'Enter your E-mail',
'class'=>'form-control'
));
echo $this->Form->input('password', array(
'placeholder'=>'Enter your password',
'class'=>'form-control'
));
?>
By default, it will recognize the password field as 'type' => 'password'
Related
I am using CakePHP 2.10.19. I have a form for entering Item Types. I also have other models for entering appropriate database objects. Error I am occurring is that my validation errors are displayed twice for this form. For other forms it works well. Here is the model:
ItemType.php
App::uses('AppModel', 'Model');
class ItemType extends AppModel {
public $classes = array(
'product' => 'Proizvod',
'kit' => 'Kit (bundle)',
'material' => 'Repromaterijal'
);
public $validate = array(
'code' => array(
'required' => array(
'rule' => 'notBlank',
'message' => 'A code is required'
),
'alphanum' => array(
'rule' => 'alphanumeric',
'message' => 'A code must be an alphanumeric value'
),
'unique' => array(
'rule' => 'isUnique',
'message' => 'This code already exists!'
),
'between' => array(
'rule' => array('lengthBetween', 3, 7),
'message' => 'Code must be between 3 and 7 characters long'
)
),
'name' => array(
'required' => array(
'rule' => 'notBlank',
'message' => 'A name is required'
),
'unique' => array(
'rule' => 'isUnique',
'message' => 'This name already exists!'
),
'between' => array(
'rule' => array('lengthBetween', 3, 30),
'message' => 'Name must be between 3 and 30 characters long'
)
),
'class' => array(
'valid' => array(
'rule' => array('inList', array('product', 'material', 'kit', 'semi_product', 'service_product', 'service_supplier','consumable','inventory','goods','other')),
'message' => 'Please enter a valid class',
'allowEmpty' => false
)
),
'tangible' => array(
'bool' => array(
'rule' => 'boolean',
'message' => 'Incorrect value for the checkbox'
)
),
'active' => array(
'bool' => array(
'rule' => 'boolean',
'message' => 'Incorrect value for the checkbox'
)
)
);
public $hasMany = array(
'Item' => array(
'className' => 'Item',
'foreignKey' => 'item_type_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
)
);
}
ItemTypesController.php
<?php
class ItemTypesController extends AppController {
public function add() {
if ($this->request->is('post')) {
$this->ItemType->set($this->request->data);
if($this->ItemType->validates()){
debug($this->ItemType->validates());
$this->ItemType->create();
if ($this->ItemType->save($this->request->data)) {
$this->Flash->success(__('The item type has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
debug($this->ItemType->invalidFields());
$this->Flash->error(__('The item type could not be saved. Please, try again.'));
}
}
debug($this->ItemType->invalidFields());
$this->Flash->warning($this->ItemType->validationErrors, array(
'key' => 'negative'
));
}
$this->set('classes', $this->ItemType->classes);
}
}
Also, debug($this->ItemType->invalidFields()) is showing array with two fields for each field, like this:
array(
'code' => array(
(int) 0 => 'Code must be between 3 and 7 characters long',
(int) 1 => 'Code must be between 3 and 7 characters long'
),
'name' => array(
(int) 0 => 'Name must be between 3 and 30 characters long',
(int) 1 => 'Name must be between 3 and 30 characters long'
)
)
...so I am guessing a model is making some sort of mistake.
add.ctp
<div class="itemTypes form">
<?php echo $this->Form->create('ItemType'); ?>
<fieldset>
<legend><?php echo __('Add Item Type'); ?></legend>
<?php
echo $this->Form->input('code');
echo $this->Form->input('name');
echo $this->Form->input('class', array('options' => $classes));
echo $this->Form->input('tangible');
echo $this->Form->input('active');
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
Anyone has an idea. Thing is, other controllers have basically the same logic but do not have this sort of a mistake where validation errors are displayed twice.
Generally this is because validation is triggered twice. This is triggered twice, once when you call $this->ItemType->validates()) and another time when you call debug($this->ItemType->invalidFields());
Please comment and remove all the debug statements.
Apparently upon removing the debug statements it works like it should with only one validation error per type as it should do. Not sure why debug made problem tho.
Insde the User Model
App::uses('SimplePasswordHasher','Controller/Component/Auth');
class User extends AppModel {
public $useTable = 'users';
public $hasMany = array(
'Reminder' => array(
'className' => 'Reminder'
)
);
public $validate = array(
'username' => array(
'alphaNumeric' => array(
'rule' => 'alphaNumeric',
'required' => true,
'message' => 'Alphabets and numbers only'
),
'between' => array(
'rule' => array('between',5,15),
'message' => 'Between 5 to 15 characters'
),
'unique' => array(
'rule' => 'isUnique',
'message' => 'Username is already taken'
)
),
'password' => array(
'between' => array(
'rule' => array('between',5,10),
'message' => 'Between 5 to 10',
),
'compareFields' => array(
'rule' => array('compareFields','confirm_password'),
'message' => 'Passwords do not match',
'required' => 'update'
)
),
'email' => array(
'email' => array(
'rule' => 'email',
'message' => 'Please enter valid email address'
),
'unique' => array(
'rule' => 'isUnique',
'message' => 'Email is already in use'
),
'compareFields' => array(
'rule' => array('compareFields','confirm_email'),
'message' => 'Emails do not match',
'required' => 'update'
)
),
'timezone' => array(
'isValid' => array(
'rule' => 'isValid',
'message' => 'Please select a timezone'
)
)
);
Inside the User Controller.
// Changed existing emails
if(!empty($this->request->data['User']['email'])) {
echo "Email is set <br/>";
$this->User->set($this->request->data['User']['email']);
if($this->User->validates(array('fieldList' => array('email')))) {
echo "Email is valid <br/>";
$this->User->id = $this->Session->read('Auth.User.id');
$this->User->saveField('email',$this->request->data['User']['email'],true);
$this->Session->setFlash("Settings updated");
}
}
// Change existing password
if(!empty($this->request->data['User']['password'])) {
echo "Password is set <br/>";
$this->User->set($this->request->data['User']['password']);
if($this->User->validates(array('fieldList' => array('password')))) {
echo "Password is valid <br/>";
$this->User->id = $this->Session->read('Auth.User.id');
$this->User->saveField('password', $this->request->data['User']['password'],true);
$this->Session->setFlash("Password changed");
}
}
I know 'saveField()' doesn't do validation automatically so I've set the validation parameter to true, but to no avail.
I've included the models containing the validations.
Any help would be appreciated.
Edited:
I actually ment that you had to do the validation like this:
$this->User->id = $this->Session->read('Auth.User.id');
if(!$this->User->saveField('password', 'asdf', true)) {
echo "Invalid.";
pr($this->User->invalidFields());
} else {
echo "Saved!";
}
or optionally, do this:
Just read() the data, overwrite the new password in that array, then $this->User->set() and use $this->User->validates() like you have.
See here.
I followed this post for password confirmation, but CakePHP seems to be skipping over my re_password validation settings.
Here's my form
<?php echo $this->Form->create('User'); ?>
<fieldset>
<legend><?php echo __('Add Account'); ?></legend>
<?php
echo $this->Form->input('username');
echo $this->Form->input('email');
echo $this->Form->input('password');
echo $this->Form->input('re_password', array('type'=>'password', 'label'=>'Re-Enter Password', 'value'=>''));
echo $this->Form->input('role', array('type' => 'hidden', 'default' => 'user'));
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
This is in my User model
function equalToField($array, $field) {
return strcmp($this->data[$this->alias][key($array)], $this->data[$this->alias][$field]) == 0;
}
public $validate = array(
'username' => array(
'required' => array(
'rule' => array('minLength', '3'),
'message' => 'A username with a minimum length of 3 characters is required'
),
'unique' => array(
'rule' => 'isUnique',
'message' => 'This username has already been taken.'
)
),
'email' => array(
'email' => array(
'rule' => array('email'),
'message' => 'Please enter a valid email address.',
)
),
'password' => array(
'required' => array(
'rule' => array('minLength', '8'),
'message' => 'A password with a minimum length of 8 characters is required'
)
),
're_password' => array(
'required' => array(
'rule' => array('equalToField', 'password'),
'message' => 'Passwords do not match'
)
)
);
An error occurs if the minlength rule was triggered for the password field, but nothing ocurrs for the re_password field
I deleted the equalToField method just to see what would happen. I didn't even get an error so it seems as if re_password isn't even being looked at.
I'm not sure if this has anything to do with it, but when I added an additional rule to the password field regarding re_password, I got the following error: "Undefined index: re_password [APP/Model/User.php"
'password' => array(
'required' => array(
'rule' => array('minLength', '8'),
'rule' => array('equalToField', 're_password'),
'message' => 'A password with a minimum length of 8 characters is required'
)
),
Also, in my UsersController action I printed(this->request->data) and the re_password field is set.
For CakePHP2 you can use something like this:
public $validate = array(
'password' => array(
'length' => array(
'rule' => array('minLength', '8'),
'message' => 'Password should have at least 8 chars.'
)
),
'password_confirmation' => array(
'length' => array(
'rule' => array('minLength', '8'),
'message' => 'Password should have at least 8 chars.'
),
'compare' => array(
'rule' => array('validate_passwords'),
'message' => 'Passwords are not same.',
)
),
);
public function validate_passwords() {
return $this->data[$this->alias]['password'] === $this->data[$this->alias]['password_confirmation'];
}
This is working for me, Try with this..
public $validate = array(
'password' => array(
'minLength' => array(
'rule' => array('minLength', 4),
'message' => 'Password must be at least 4 characters long'
),
'maxLength' => array(
'rule' => array('maxLength', 50),
'message' => 'Password cannot be longer than 50 characters'
),
'notEmpty' => array(
'rule' => 'notEmpty',
'message' => 'Please enter a password'
)
),
'confirm_password' => array(
'passwordMatch' => array(
'rule' => array('identicalFieldValues', 'password'),
'message' => 'The two passwords you entered do not match, please try again'
),
'notEmpty' => array(
'rule' => 'notEmpty',
'message' => 'Please confirm your password by entering it twice'
)
)
);
I have a form that requires that all fields are filled in.
Upon submit, it should validate, before doing anything else. However, it submits even if there are some fields that were not filled in.
I've searched on here, but can't seem to find anything that is off use for me.
Here is my method in my InductionPpe controller:
public function request() {
if ($this->request->is('post')) {
$this->InductionPpe->set($this->request->data);
if($this->InductionPpe->validates()) {
// carry on
} else {
$this->validateErrors($this->InductionPpe);
$this->render();
}
}
}
My model has all the rules for the fields set up and completes the rest of the process just fine. But it does not validate.
Where do I start looking for the issue? And how do I fix it?
UPDATE
Validation rules in the InductionPpe Model:
class InductionPpe extends AppModel {
/**
* Validation rules
*
* #var array
*/
public $validate = array(
'hr_employee_id' => array(
'numeric' => array(
'rule' => array('numeric')
),
),
'name' => array(
'notempty' => array(
'rule' => array('notempty'),
'message' => 'Please enter your name.'
),
),
'shoes' => array(
'notempty' => array(
'rule' => array('notempty'),
'message' => 'Please enter the shoe size required.'
),
),
'reflective_jacket' => array(
'notempty' => array(
'rule' => array('notempty'),
'message' => 'Please enter the size reflective jacket required.'
),
),
'metaguards' => array(
'notempty' => array(
'rule' => array('notempty'),
'message' => 'Please enter the size of metaguards required.'
),
),
'glasses' => array(
'notempty' => array(
'rule' => array('notempty'),
'message' => 'Please enter the number of glasses required.'
),
),
'earplugs' => array(
'notempty' => array(
'rule' => array('notempty'),
'message' => 'Please enter the amount of earplugs reguired.'
),
),
'hardhats' => array(
'notempty' => array(
'rule' => array('notempty'),
'message' => 'Please enter the amount of hardhats required.'
),
),
'gloves' => array(
'notempty' => array(
'rule' => array('notempty'),
'message' => 'Please enter the amount of gloves required.'
),
),
'kit_bags' => array(
'notempty' => array(
'rule' => array('notempty'),
'message' => 'Please enter the amount of kit bags required.'
),
),
'dust_mask' => array(
'notempty' => array(
'rule' => array('notempty'),
'message' => 'Please enter the amount of dust masks required.'
),
),
'ppe_size' => array(
'notempty' => array(
'rule' => array('notempty'),
'message' => 'Please enter the size of the PPE items.'
),
),
'activities' => array(
'notempty' => array(
'rule' => array('notempty'),
'message' => 'Please specify which activities the PPE items are required for.'
),
),
'site' => array(
'notempty' => array(
'rule' => array('notempty'),
'message' => 'Please enter the site that you will be visiting.'
),
),
'project_number' => array(
'notempty' => array(
'rule' => array('notempty'),
'message' => 'Please enter the project number applicable.'
),
),
'date_required' => array(
'notempty' => array(
'rule' => array('notempty'),
'message' => 'Please enter the date that the PPE equipment is required.'
),
)
);
}
UPDATE 2
This is the validation debug I get (if I run debug($this->InductionPpe->validationErrors);).
array(
'name' => array(
(int) 0 => 'Please enter your name.'
),
'shoes' => array(
(int) 0 => 'Please enter the shoe size required.'
),
'reflective_jacket' => array(
(int) 0 => 'Please enter the size reflective jacket required.'
),
'metaguards' => array(
(int) 0 => 'Please enter the size of metaguards required.'
),
'glasses' => array(
(int) 0 => 'Please enter the number of glasses required.'
),
'earplugs' => array(
(int) 0 => 'Please enter the amount of earplugs reguired.'
),
'hardhats' => array(
(int) 0 => 'Please enter the amount of hardhats required.'
),
'gloves' => array(
(int) 0 => 'Please enter the amount of gloves required.'
),
'kit_bags' => array(
(int) 0 => 'Please enter the amount of kit bags required.'
),
'dust_mask' => array(
(int) 0 => 'Please enter the amount of dust masks required.'
),
'ppe_size' => array(
(int) 0 => 'Please enter the size of the PPE items.'
),
'activities' => array(
(int) 0 => 'Please specify which activities the PPE items are required for.'
),
'site' => array(
(int) 0 => 'Please enter the site that you will be visiting.'
),
'project_number' => array(
(int) 0 => 'Please enter the project number applicable.'
),
'date_required' => array(
(int) 0 => 'Please enter the date that the PPE equipment is required.'
)
)
And my form where these are entered:
<div class="inductionPpes form">
<?php
echo $this->Form->create('PpeRequest',array('type' => 'file')); ?>
<fieldset>
<legend><?php echo __(' PPE Request'); ?></legend>
<?php
echo $this->Form->input('name',array('value'=>$loggedInUsersName));
echo $this->Form->input('shoes');
echo $this->Form->input('reflective_jacket');
echo $this->Form->input('metaguards');
echo $this->Form->input('glasses');
echo $this->Form->input('earplugs');
echo $this->Form->input('hardhats');
echo $this->Form->input('gloves');
echo $this->Form->input('kit_bag');
echo $this->Form->input('dust_masks');
echo $this->Form->input('ppe_size');
echo $this->Form->input('activities',array('label'=>'Type of activities that will be undertaken'));
echo $this->Form->input('additional',array('label'=>'Additional PPE Requirements'));
echo $this->Form->input('site',array('label'=>'Type of Site'));
echo $this->Form->input('project_number');
echo $this->Form->input('date_required');
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
</div>
Try changing the notempty rule to this
'notempty' => array(
'required' => true,
'allowEmpty' => false, // this may not be neccessary
'rule' => 'notEmpty',
'message' => 'Please enter the ...',
)
The problem may be that you wrapped validation rule names in an array. AFAIK only rules with parameters should be entered this way.
Also I don't know about $this->validateErrors and whether such variable exists but I always use $this->Model->validationErrors
Try this (with all your notempty validations)
'name' => array(
'notempty' => array(
'rule' => array('notempty'),
'message' => 'Please enter your name.',
'required' => true,
'allowEmpty' => false
),
),
putting required and allowEmpty on bottom. Also, reading your comments, you mention the error blocks doesn't show. Read this post, if you do $this->Model->save(), it'll take care of that, otherwise you'll have to do it.
I want to be able to delete a user, but when I try to it throws the following error. "Error: The requested address '/cakephp/users/delete/8?url=users%2Fdelete%2F8' was not found on this server."
The code for my delete function is
public function delete($id = null)
{
debug($this->User->delete());
if (!$this->request->is('get'))
{
throw new MethodNotAllowedException();
}
if ($this->User->delete($id))
{
$this->Session->setFlash('The user with id: ' . $id . ' has been deleted.');
$this->redirect(array('action' => 'usermanage'));
}
}
[NEW]
I got rid of the usermanagement code and the index code to make room for my user model code..
<?php
App::uses('AuthComponent', 'Controller/Component');
class User extends AppModel {
public $primary_key = 'userID';
public $validate = array(
'username' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A username is required'
)
),
'password' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A password is required'
)
),
'name' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'Your name is required'
)
),
'surname' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'Your surname is required'
)
),
'memberType' => array(
'valid' => array(
'rule' => array('inList', array('admin', 'responder', 'volunteer')),
'message' => 'Please enter a valid role',
'allowEmpty' => false
)
),
'address1' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'Please enter your first line of address'
)
),
'address2' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'please enter your second line of address'
)
),
'town' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'Please enter your town'
)
),
'postCode' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'please enter your postcode'
)
),
'dob' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'please enter your date of birth'
)
),
'emailAddress' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'please enter your email address'
)
),
'phoneNumber' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'please enter your phone number'
)
),
'mobileNumber' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'please enter your mobile number'
)
)
);
public function beforeSave($options = array()) {
if (isset($this->data[$this->alias]['password'])) {
$this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
}
}
}
?>
Any help will be appreciated!
This error can be corrected in two ways (pickup one):
1 - Change your action delete to:
if (!$this->request->is('post') && !$this->request->is('put')) {
throw new MethodNotAllowedException();
}
2 - Not use postLink, and change delete action:
<?php echo $this->Html->link('Delete', array('controller' => 'users', 'action' => 'delete', $user['User']['userID'])); ?>
public function delete($id = null) {
$this->User->id = $id;
if(!$this->User->exists()) {
throw new NotFoundException(__('Invalid user'));
}
if ($this->User->delete($id)) {
$this->Session->setFlash('The user with id: ' . $id . ' has been deleted.');
$this->redirect(array('action' => 'usermanage'));
}
}
[EDIT]
For your primaryKey problem:
In User model:
public $primary_key = 'userID';
In Other models (belongsTo, hasMany, hasBelongsToMany):
public $belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'userID'
)
);
Sorry for my english, I'm brazilian.