CakePHP Validation - php

How do I show the messages when using the CakePHP validation? As I creating the input fields manually using input() instead using the shorthand form() helper.
e.g. Form:
<?php echo $this->Form->create('User', array('id' => 'loginform', 'type' => 'post',
'url' => array('controller' => 'users', 'action' => 'login'))); ?>
<fieldset id="login">
<ul class="clearfix">
<li id="li-username">
<?php echo $this->Form->input('email', array( 'label' => array('class' => 'placeholder', 'text' => 'Email address or username') )); ?>
</li>
<li id="li-password">
<?php echo $this->Form->input('password', array( 'type' => 'password', 'label' => array('class' => 'placeholder', 'text' => 'Password') )); ?>
<span id="iforgot"><?php echo $this->Html->link('?',
array('controller' => 'users', 'action' => 'forgotpassword'), array('title' => 'Forgot your password?')); ?></span>
</li>
<li id="li-submit">
<button type="submit" title="Log in">Log in ►</button>
</li>
</ul>
</fieldset>
<?php echo $this->Form->end(); ?>
and this is my validation in the user model:
public $validate = array(
'email' => array(
'valid' => array(
'rule' => 'email',
'message' => 'The email is not valid'
),
'required' => array(
'rule' => 'notEmpty',
'message' => 'Please enter an email'
)
)
);
However the validation error messages don't show?
EDIT:
I tested this on my register form at /users/add/ and it works so it seems that the auto validation does not work with the login method???? How do I add validation for the login form then :/

The validation is actually stored in the model object. I'm not entirely sure off-hand how to access the errors, but I think its in $this->User->validationErrors.
Have a look at the model api for more information.
For logging in, use the auth component. If you'd rather not, then just get the user from the db and display an error using $this->Session->SetFlash() if the user doesn't authenticate.

You can show your code login function?
I think in your code that have redirect in-case validate false
If you use $this->redirect() it'll not show validate messages :)

First you check your post data is going to validate function.you can simple check this in your else condition like this :
$this->{$this->modelClass}->set($this->data);
if($this->{$this->modelClass}->validates(){
//Save data in DB
}else{
pr($this->{$this->modelClass}->validationErrors); // This will show your error message
}
You can also show error in your view.ctp file like this
$errors = '';
foreach ($this->validationErrors[$model] as $key => $validationError) {
$errors .= $this->Html->tag('li', $validationError[0]);
}
echo $this->Html->tag('ul', $errors,array('class' => 'error'));

Related

CakePHP authentication: Invalid salt / invalid username or password?

I'm going through the CakePHP tutorial and trying to test basic login functionality. I'm making slight tweaks along the way to match how my database needs to look (email and token instead of username and password as columns in the users table), I believe that I have messed something up when it comes to using Blowfish hashing. Can someone take a look and see if anything apparent pops out? Right now I can add new users, but their password in the database look to be plaintext. The token column is of type VARCHAR(75), is that enough space for Blowfish to work?
I'm getting the error:
**Warning (512): Invalid salt: pass for blowfish **
and then "Invalid username or password," when putting in a correct user/pass combo. When I put in incorrect credentials I only get the invalid user/pass error, so it looks like it is still getting through somewhere along the line.
app/Model/User.php
App::uses('AppModel', 'Model');
App::uses('BlowfishPasswordHasher', 'Controller/Component/Auth');
class User extends AppModel {
public $validate = array(
'email' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'An email is required'
)
),
'token' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A password is required'
)
),
'group' => array(
'valid' => array(
'rule' => array('inList', array('user', 'admin', 'manager')),
'message' => 'Please enter a valid group role',
'allowEmpty' => false
)
)
);
public function beforeSave($options = array()) {
if (isset($this->data[$this->alias]['token'])) {
$passwordHasher = new BlowfishPasswordHasher();
$this->data[$this->alias]['token'] = $passwordHasher->hash(
$this->data[$this->alias]['token']
);
}
return true;
}
}
app/Controller/AppController.php
class AppController extends Controller {
//...
public $components = array(
'Session',
'Auth' => array(
'loginRedirect' => array(
'controller' => 'posts',
'action' => 'index'
),
'logoutRedirect' => array(
'controller' => 'pages',
'action' => 'display',
'home'
),
'authenticate' => array(
'Form' => array(
'passwordHasher' => 'Blowfish',
'fields' => array('username' => 'email', 'password' => 'token')
)
)
)
);
public function beforeFilter() {
$this->Auth->allow('index', 'view');
}
//...
}
add.ctp
<div class="users form">
<?php echo $this->Form->create('User'); ?>
<fieldset>
<legend><?php echo __('Add User'); ?></legend>
<?php echo $this->Form->input('email');
echo $this->Form->input('token');
echo $this->Form->input('group', array(
'options' => array('admin' => 'Admin', 'manager' => 'Manager', 'user' => 'User')
));
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
</div>
login.ctp
<div class="users form">
<?php echo $this->Session->flash('auth'); ?>
<?php echo $this->Form->create('User'); ?>
<fieldset>
<legend>
<?php echo __('Please enter your username and password'); ?>
</legend>
<?php echo $this->Form->input('email');
echo $this->Form->input('token');
?>
</fieldset>
<?php echo $this->Form->end(__('Login')); ?>
</div>
Check the blowfish salt to make sure it has the correct number of characters, and use the add / edit form to set the password initally.
You should also set the token length in the db to 256 chars

Cakephp Model won't save form input

I have a very simple model User, and it's associated table users with fields 'id', 'username', 'password', 'role', 'created', 'modified'.
The view add.ctp contains:
<div class="users form">
<?= $this->Form->create('user'); ?>
<fieldset>
<legend><?= __('Add user');?></legend>
<?= $this->Form->input('user.username'); ?>
<?= $this->Form->input('password'); ?>
<?= $this->Form->input('role', array('options' => array('admin' => 'Admin', 'customer' => 'Customer'))); ?>
</fieldset>
<?= $this->Form->end(__('Submit')); ?>
</div>
The model is set up according to http://book.cakephp.org/2.0/en/tutorials-and-examples/blog-auth-example/auth.html:
class User extends AppModel {
public $validate = array(
'username' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'You must specify a username'
)
),
'password' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'You must specify a password'
)
),
'role' => array(
'valid' => array(
'rule' => array('inList', array('admin','customer')),
'message' => 'You must specify a valid role',
'allowEmpty'=> false
)
)
);
}
And lastly, the controller simply has:
public function add() {
if($this->request->is('post')) {
$this->User->create();
if ($this->User->save($this->request->data)) {
$this->set('stuff', $this->User->data);
$this->Session->setFlash(__('The user has been saved.'));
//return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please try again.'));
}
}
}
I've commented out the redirect on success to be able to show the INSERT query on submit (if I allow the redirect, the only query being shown is SELECT's)
So, quite simple, the problem is, when the form is submitted, it generates this query:
INSERT INTO `mytable`.`users` (`modified`, `created`) VALUES ('2014-02-21 13:03:11', '2014-02-21 13:03:11')
How can I determine why it won't insert the submitted fields? And how can I make it?
use this <?= $this->Form->create('User'); ?> instead of <?= $this->Form->create('user'); ?>
and use this <?= $this->Form->input('User.username'); ?> instead of <?= $this->Form->input('user.username'); ?>
CakePHP is case sensitive model name must be in CamalCase

Show the correct error validation messages

I have a page with 2 forms on it: a registration form and a login form. Each form has a submit button. Now I'm validating both forms, but for example if I press the submit button of the registration form I'd like only to show the error messages of the registration form and not of the login form. At the moment both error message are being shown. Is there a way around this?
<div class="grid-container">
<div class="grid-50 login">
<h3>Inloggen</h3>
<?php
$loginEmail = array('placeholder' => "Email", 'name' => "loginEmail");
$loginPassword = array('placeholder' => "Wachtwoord", 'name' => "loginPassword");
$loginSubmit = array('name' => "loginSubmit", 'class' => "btn", 'value' => "Inloggen");
$loginForgot = array('name' => "loginForgot", 'class' => "link", 'value' => "Wachtwoord vergeten?");
echo form_open('login/inloggen', array('class' => 'grid-100 formc'));
echo form_input($loginEmail);
echo form_password($loginPassword);
echo form_submit($loginSubmit);
echo form_submit($loginForgot);
echo form_close();
?>
<?php echo validation_errors('<p class="error">');?>
</div>
<div class="grid-50 login">
<h3>Registreren</h3>
<?php
$registerName = array('placeholder' => "Naam", 'name' => "registerName");
$registerEmail = array('placeholder' => "Email", 'name' => "registerEmail");
$registerPassword = array( 'placeholder' => "Wachtwoord", 'name' => "registerPassword");
$registerSubmit = array('name' => "registerSubmit", 'class' => "btn", 'value' => "Registreer");
echo form_open('login/register');
echo form_input($registerName, set_value('registerName'));
echo form_input($registerEmail, set_value('registerEmail'));
echo form_password($registerPassword);
echo form_submit($registerSubmit);
echo form_close();
?>
<?php echo validation_errors('<p class="error">');?>
</div>
Validation in the controller
$this->form_validation->set_rules('registerEmail', 'Email verkeerd', 'trim|required|valid_email');
$this->form_validation->set_rules('registerPassword', 'Password te kort', 'trim|required|min_length[4]');
it would be nicer if you create different rules for the login and for you're registration.
how?
create a Form_validation.php file on application/libraries
inside specify the rules for you're login and register example
$config = array(
'login_validation_rules'=>array(
array(
'field' => 'username',
'label' => 'The User Name',
'rules' => 'required'
),
array(
'field' => 'password',
'label' => 'The Password',
'rules' => 'required'
)
),
'registration_validation_rules'=>array(
array(
'field' => 'email',
'label' => 'The Email',
'rules' => 'required|valid_email'
),
array(
'field' => 'firstname',
'label' => 'The Firstname',
'rules' => 'required'
)
)
);
Then on you're controller you can catch what form they are submitting and what validation rules to use example
if($this->input->post('registerSubmit'))
{
if($this->form_validation->run('registration_validation_rules') == FALSE)
{
//error
}else{
//good
}
}elseif($this->input->post('loginSubmit')){
if($this->form_validation->run('login_validation_rules') == FALSE)
{
//error
}else{
//good
}
}
At the same time you're controller will not be cluttered with rules. makes reading easier you can read more of this on the Codigniter manual - validation config file
Do you use two submit in one page? try to make one to submit through javascript or jquery
be cause when you submit the submit it submit the whole page in some browsers
also try this show validate error for each fields
<?=form_error('loginEmail')?>
<?=form_error('registerPassword')?>

CakePHP error validation

I have a cakephp form that has validation. The validation itself works BUT when an error shows up after clicking submit, it just produces some text.
Why am I getting no colour. eg Its meant to display errors in red.
Controller
<div class="users form">
<?php echo $this->Form->create('Ticket'); ?>
<fieldset>
<legend><?php echo __('Purchase'); ?></legend>
<?php
echo $this->Form->input('first_name');
echo $this->Form->input('last_name');
echo $this->Form->input('email');
echo $this->Form->input('phone');
echo $this->Form->input('date', array('options'=> $dates));
echo $this->Form->input('quantity', array('options' => $maxAmount, 'default' => '1'));
?>
</fieldset>
<?php
echo $this->Form->end(__('Purchase'));
?>
</div>
Model
public $validate = array(
'first_name' => array(
'rule' => '/^[a-zA-Z]{1,}$/i',
'message' => 'Alphabets only',
'required' => true
),
'last_name' => array(
'rule' => '/^[a-zA-Z]{1,}$/i',
'message' => 'Alphabet only',
'required' => true
),
'phone' => array(
'rule' => 'numeric',
'message' => 'numbers only please',
'required' => true
),
'email' => array(
'rule' => 'email',
'message' => 'Your email is not valid',
'required' => true
),
'quantity' => array(
'rule' => 'numeric',
'message' => 'numbers only please',
'required' => true
)
);
Did you include a stylesheet in your default.ctp? If you removed the default CakePHP stylesheet from your default.ctp layout, the default colours will no longer be there.
You need to either include the CakePHP stylesheet again in your layout (here you can see how it was in the original default.ctp: https://github.com/cakephp/cakephp/blob/master/app/View/Layouts/default.ctp#L33)
Or create your own CSS styles in your stylesheet. You can use the styles from the default CakePHP stylesheet as an example;
https://github.com/cakephp/cakephp/blob/master/app/webroot/css/cake.generic.css#L371
There is nothing wrong with your code. That is just how CakePHP is handling the error reporting. The red stuff is reserved for major errors like missing view, or a missing function, or cant connect to the database. Basically stuff that would generate a status code that is in the range of 400.
I did some searching to answer your question better, but i stumbled on this page.
CakePHP 2.0 - How to make custom error pages?
Its all about what status code CakePHP will generate when u do something wrong.
Validation errors will I think throw even an OK (200) but wont write anything to the database. Happened a couple a times to me.

CakePHP not checking form validation

I'm writing a contact form and want to add some simple validation routines. The action for this page looks like this:
public function contact() {
$this->loadModel('Contact');
$this->set('pageTitle', 'Contact me');
}
and the Contact model is this:
<?php
class Contact extends AppModel {
public $useTable = false;
public $validate = array(
'name' => array(
'between' => array(
'rule' => array('between', 1, 60),
'message' => 'Between 1 and 60 characters in length'
)
),
'email' => array(
'kosher' => array(
'rule' => 'email',
'message' => 'Please make sure your email is entered correctly'
),
),
'message' => array(
'between' => array(
'rule' => array('between', 1, 65000),
'message' => 'Between 1 and 65000 characters in length'
)
)
);
}
and finally my view page:
<?php echo $this->Form->create('Contact'); ?>
<?php echo $this->Form->input('name'); ?>
<?php echo $this->Form->input('email'); ?>
<?php echo $this->Form->input('message', array('type' => 'textarea')); ?>
<?php echo $this->Form->end(array('label' => 'Send', 'class' => 'btn btn-primary')); ?>
However, when I submit the form with incorrect values the validation routines aren't called and no error messages are shown.
How can I get Cake to validate the form?
In your contact action all you are doing is loading the Contact model. You have to explicitly call the relevant model method to perform validation. Read the manual properly for how to do that.
Look in the documentation for how to insert/update data from a form in the controller. You'll see something like this:
if ($this->request->is('post')) {
if ($this->Contact->save($this->request->data)) {
// handle the success.
} else {
$this->Session->setFlash(__('The Contact could not be saved. Please, try again.'));
}
}

Categories