cake 2.1 data validation not working - cakephp-2.1

I tried every method, but it cake php data validation does not working.would you tell me what is the wrong part?
I add all types of validations but still the form saves without validation data!
My model:
class contacts extends AppModel
{
public $name = 'contact';
public $useTable='contacts';
public $validate=array(
'name' => array(
'requierd'=>array(
'rule'=>array('Not empty'),
'message' => 'A username is required'
)
)
);
}
My controller
class ContactsController extends AppController
{
public $helpers=array('Html','Form');
public $components=array('session','Email');
public function index()
{
if($this->request->is('post'))
{
$this->Contact->create();
if($this->Contact->save($this->request->data))
{
$this->Session->setFlash('Thank you we will contact you soon');
$this->redirect(array('action'=>'index'));
}
else
{
$this->Session->setFlash('Unable to send your message.');
}
}
}
}
My view:
echo $this->Form->create('Contact');
echo $this->Form->input('name');
echo $this->Form->input('email');
echo $this->Form->input('subject');
echo $this->Form->input('message',array('rows' => '3'));
//echo $this->Form->checkbox('Send me a coppy');
echo $this->Form->end('Send');

Try with
public $validate=array(
'name' => array(
'rule' => 'notEmpty',
'message' => 'A username is required'
)
);
as seen in the docs example. Don't know why you added an extra array.
You can add required and allowEmpty indexes just to be strict-er
public $validate=array(
'name' => array(
'rule' => 'notEmpty',
'message' => 'A username is required',
'required' => true,
'allowEmpty' => false
)
);

I figured it out. the reason that they were not working was because the model name!!

Related

nothing is working except 'not empty' validation in cakephp

I'm new to CakePHP. I'm validating my form, but the problem is that no validation is working except the not empty validation.
My model file is:
class User extends AppModel {
public $name = 'User';
public $validate = array(
'rule_name' => array(
'alphaNumeric' => array(
'rule' => 'Numeric',
'required' => true,
'message' => 'Letters and numbers only'
)
)
);
}
My View file is:
echo $this->Form->create('User');
echo $this->Form->input('rule_name',array('class'=>'form-control','autocomplete'=>'off'));
Please suggest how I can fix this.
General usage pattern adding a rule for a single field:
public $validate = array(
'fieldName1' => array(
'rule' => 'ruleName',
'required' => true,
'allowEmpty' => false,
'message' => 'Your Error Message'
)
);
Must be look at Data Validation in cakePHP

CodeIgniter custom validation library function not working

I've created custom validation library class MY_Form_validation as MY_Form_validation.php in application/libraries as follows.
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class MY_Form_validation extends CI_Form_validation {
public function __construct($rules = array()) {
parent::__construct($rules);
}
public function file_required($file) {
if($file['size']===0) {
$this->set_message('file_required', 'Uploading a file for %s is required.');
return false;
}
return true;
}
}
?>
In my validation function I've included following rules as follows.
public function validate() {
$this->load->library('form_validation');
$config = array(
array(
'field' => 'name',
'label' => 'Name',
'rules' => 'trim|required|xss_clean'
),
array(
'field' => 'display_photo',
'label' => 'Display Photo',
'rules' => 'trim|good|file_required|xss_clean'
),
);
$this->form_validation->set_rules($config);
if ($this->form_validation->run()) {
return true;
}
return false;
}
The core validation rules are working fine but custom rule is not working. So please help me to get the soultion and Its literally wasting my time. The work would be more appreciated.
As far as i understand your function always return true. Because of $file Not $_FILES
public function file_required($file) {
if($_FILES[$file]['size']===0) {
$this->set_message('file_required', 'Uploading a file for %s is required.');
return false;
}
return true;
}
Check the rules in the function validate()
What I think it's incorrect:
$config = array(
array(
'field' => 'name',
'label' => 'Name',
'rules' => 'trim|required|xss_clean'
),
array(
'field' => 'display_photo',
'label' => 'Display Photo',
'rules' => 'trim|good|file_required|xss_clean'
),
);
What I think is correct:
$config = array(
array(
'field' => 'name',
'label' => 'Name',
'rules' => 'trim|required|xss_clean'
),
array(
'field' => 'display_photo',
'label' => 'Display Photo',
'rules' => 'trim|file_required|xss_clean'
),
);
I think good is not a php function, or an internal codeigniter function.
Edit:
What about using:
if ($file['size'] == 0) {
Instead of
if ($file['size'] === 0) {
Using === means the value MUST BE integer 0, but if $file['size'] returns 0 as string the if won't be true, and the function always will return true.
I had the same problem and found the cause while looking in CodeIgniter's source code. It seems the writers thought that if a field didn't have "required", then it would just skip all the rules and always return that the form has validated. See it for yourself from their code:
// If the field is blank, but NOT required, no further tests are necessary
if ( ! in_array('required', $rules) AND is_null($postdata))
However, if you add "callback_" in front of your rule, you can still make it run, for the procedure, look here:
https://www.codeigniter.com/userguide2/libraries/form_validation.html#callbacks

Validate form fields in controller with a hasMany relation

I'm having some issues with validating form fields inside my controller, for testing purposes.
I have my model Experience with hasMany ExperienceDetail. ExperienceDetail belongsTo Experience.
I created a form using the FormHelper which contains the following:
index.ctp
<?php
echo $this->Form->create('Experience', array('action' => 'index'));
echo $this->Form->input('Experience.date', array(
'label' => array(
'text' => 'Datum'),
'type' => 'date',
'dateFormat' => 'DMY',
'monthNames' => false,
'minYear' => date('Y') - 10,
'maxYear' => date('Y')
)
);
echo $this->Form->input('Experience.test');
echo $this->Form->input('ExperienceDetail.vertrekstation');
echo $this->Form->end('Verstuur!');
?>
There are some more fields provided with ExperienceDetail, but these are irrelevant for this matter.
Experience.php
<?php
class Experience extends AppModel {
public $name = 'Experience';
public $hasMany = 'ExperienceDetail';
public $validate = array(
'vertrekstation' => array(
'rule' => 'notEmpty',
'message' => 'Voer een vertrekstation in',
'required' => true
),
'test' => array(
'rule' => 'notEmpty',
'message' => 'Test mag niet leeg zijn!'
)
);
}
?>
ExperienceDetail.php
<?php
class ExperienceDetail extends AppModel {
public $name = 'ExperienceDetail';
public $belongsTo = 'Experience';
public $validate = array(
'vertrekstation' => array(
'rule' => 'notEmpty',
'message' => 'Voer een vertrekstation in'
)
);
}
?>
ExperiencesController.php
<?php
class ExperiencesController extends AppController {
public $helpers = array('Html', 'Form', 'Session');
public function index() {
// $this->layout = 'default_orig';
$this->set('title_for_layout', 'De OV-Ervaringenmeter!');
// LOAD Model Carrier
$this->loadModel('Carrier');
$this->set('carrier', $this->Carrier->find('list', array('order' => array('Carrier.name' => 'asc'))));
// Check if form is allready filled
if($this->request->is('post')) {
$this->Experience->set($this->request->data);
$this->Session->setFlash('No if or else statement is called');
if ($this->Experience->validates()) {
$this->Session->setFlash('Validates!');
}
}
}
}
?>
The problem is: when I send the form and leave test empty, it provides me the validation error which I've set up in the Model. But when I leave vertrekstation empty, it doesn't provide me any errors that belongs to the input field.
What am I doing wrong and how am I able to get these errors printed?

CakePHP validation always true

I've been struggling with this for the last hour or so, wondering if some fresh eyes can help.
Model
class User extends AppModel {
public $name = 'User';
public $validate = array(
'email' => array(
'valid' => array(
'rule' => 'email',
'message' => 'The email is not valid'
),
'required' => array(
'rule' => 'notEmpty',
'message' => 'Please enter an email'
)
)
);
}
Controller
class UserController extends AppController {
var $uses = array('User');
function index(){
$users = $this->User->find('all');
$this->set(compact('users'));
}
public function add() {
$this->set('title_for_layout', 'Add new user');
if(isset($this->data) && !empty($this->data)) {
$this->User->set($this->data);
$this->log($this->User->invalidFields(), "debug");
if($this->User->validates()){
if ($this->User->save($this->data)) {
$this->Session->setFlash("Added " . $this->data['User']['name']);
$this->redirect('index');
}
} else {
$this->Session->setFlash('There are errors with your form submit, please see below.');
}
}
}
}
View
<?php
echo $this->Form->create('User');
echo $this->Form->input('name', array('label' => 'Name'));
echo "<div class='clear'></div>";
echo $this->Form->input('email', array('label' => 'Email'));
echo "<div class='clear'></div>";
echo $this->Form->button('Reset', array('type' => 'reset'));
echo $this->Form->button('Add Useer', array('type' => 'submit'));
echo $this->Form->end();
?>
But I never get invalid fields for email? Have I missed something glaring?
If it makes any difference, this is a plugin Im developing so it doesnt sit directly in app/ but in app/Plugins
Thanks
EDIT: So I've been struggling with this for a while now, and still no joy. One thing I have noticed though, when I print out the model details (using var_dump($this->User) ), the [validate] array is empty. For example:
[validate] => Array
(
)
[validationErrors] => Array
(
)
Im presuming this is what the issue is, even though I have declared my $validate array, its somehow being overwritten? Anyone come across this before? Any solutions?
public $validate = array(
'email' => array(
'valid' => array(
'rule' => array('email'),
'message' => 'The email is not valid'
),
'required' => array(
'rule' => array('notEmpty'),
'message' => 'Please enter an email',
'allowEmpty' => false
)
)
);
Try adding rules as array and adding 'allowEmpty' key set to false on the required validation.
Damn! So simple. If I read the cookbook properly at http://book.cakephp.org/1.3/en/view/1114/Plugin-Models it would have told me that
If you need to reference a model within your plugin, you need to include the plugin name with the model name, separated with a dot.
Thus..
var $uses = array('Plugin.User');
works.. Hope this helps someone else!

Understanding when Model's $validate rules work

I'm trying to activate a user with CakePHP 2 by activation url, but I get a validation error used on user registration page.
I've created a registration action and view, where I've defined this UserModel validation rules:
<?php
class User extends AppModel {
public $name = 'User';
public $validate = array (
'username' => array (
'not_empty' => array (
'rule' => 'notEmpty',
'message' => 'Username cannot be empty'
)
),
'password' => array (
'not_empty' => array (
'rule' => 'notEmpty',
'message' => 'Password cannot be empty'
),
'between_chars' => array (
'rule' => array ('between', 5, 40),
'message' => 'Password must be between 5 and 40 chars'
),
'match_password' => array (
'rule' => 'matchPasswords',
'message' => 'Password is different from Password confirm'
)
),
'password_confirm' => array (
'not_empty' => array (
'rule' => 'notEmpty',
'message' => 'Password confirm cannot be empty'
),
'between_chars' => array (
'rule' => array ('between', 5, 40),
'message' => 'Password confirm must be between 5 and 40 chars'
)
),
'email' => array (
'invalid_email' => array (
'rule' => 'email',
'message' => 'Invalid email, try again'
),
'existing_email' => array (
'rule' => 'isUnique',
'message' => 'This email is already registered'
)
),
'activation_key' => array (
'alphanumeric_key' => array(
'allowEmpty' => true,
'rule' => 'alphaNumeric',
'message' => 'Invalid activation key',
'last' => true
)
)
);
public function matchPasswords ($data) {
debug($this->data); // Undefined index: password_confirm [APP/Model/User.php, line 59] points here
if ($data['password'] == $this->data['User']['password_confirm']) {
return true;
}
$this->invalidate('password_confirm', 'Password confirm must be equal to Password field');
return false;
}
public function beforeSave () {
if (isset($this->data['User']['password'])) {
$this->data['User']['password'] = AuthComponent::password($this->data['User']['password']);
}
return true;
}
}
?>
Everything works perfect until I reach the activate action of the UsersController with the activation code, here I get an Undefined index: password_confirm [APP/Model/User.php, line 59] which points to matchPasswords of the User Model validation rule.
<?php
App::uses('CakeEmail', 'Network/Email');
class UsersController extends AppController {
public $name = 'Users';
public function index () {
$this->User->recursive = 0;
$this->set('users', $this->User->find('all'));
}
public function view ($id = null) {
if (!$id) {
$this->Session->setFlash('Invalid user');
$this->redirect(array('action'=>'index'));
}
$this->User->id = $id;
if (!$this->User->exists()) {
throw new NotFoundException('Invalid user');
}
$this->set('user', $this->User->read());
}
public function edit () {
}
public function delete () {
}
public function register () {
// code for user registration
}
public function registration ($sub_action = null) {
}
public function password ($sub_action = null, $code = null) {
if ($sub_action == 'reset' && !empty ($code)) {
$this->render('password_reset_code');
} else if ($sub_action == 'reset' && empty ($code)) {
$this->render('password_reset_mail');
}
}
public function login () {
if ($this->request->is('post')) {
if ($this->Auth->login()) {
$this->redirect ($this->Auth->redirect());
} else {
$this->Session->setFlash('Errore di accesso, email/password sbagliati, ricontrolla i dati inseriti');
}
}
}
public function logout () {
$this->redirect($this->Auth->logout());
}
public function activate ($code = null) {
if (!empty ($code)) {
$user = $this->User->find('first', array('conditions' => array('User.activation_key' => $code)));
if (!empty($user)) {
$user['User']['activation_key'] = null;
$user['User']['active'] = 1;
if ($this->User->save($user)) { // here is where Invalid index error starts
$this->render('activation_successful');
} else {
$this->set('status', 'Salvataggio fallito');
$this->render('activation_fail');
}
// debug($this->User->invalidFields());
// debug($this->User->data);
} else {
$this->set('status', 'Nessun account collegato alla chiave');
$this->render('activation_fail');
}
} else {
$this->set('status', 'Nessuna chiave');
$this->render('activation_fail');
}
}
private function registrationEmail ($account_email, $username, $code) {
// code for email registration
}
}
?>
Why I get the error?
Why matchPasswords is executed in the activate action?
Are these validation rules executed in every view of the controller?
Try setting the User model's id before the save in the activate() function:
$this->User->id = $user['User']['id'];
or something similar.
When you don't set the id prior to the save() function, it tries to make a new table row. That's why it's validating everything.
Try changing
if ($data['password'] == $this->data['User']['password_confirm']) {
to
if (isset($this->data['User']['password_confirm']) && $data['password'] == $this->data['User']['password_confirm']) {
in your matchPasswords function in the User.php
In the activate action you are getting all of the fields for the user and then saving them so within the data you are saving will be the password field. As the password field is there CakePHP is trying to validate it against the password_confirm field which does not exist.
You should only validate that the password and password confirm fields match when they are both present, i.e when you have the password_confirm in your form.

Resources