The Programmer
The Programmer

Reputation: 39

Validation messages are not showing in cakephp 2.4.x

Here is my validation rule in User.php

public $validate = array(
    'username' => array(
        'required' => array(
            'rule' => array('notEmpty'),
            'message' => 'User name is required'
        ),
        'alphaNumeric'=>array(
            'rule' => 'alphaNumeric',
            'required' => true,
            'message' => 'Alphabets and numbers only'
        )
    ))

and this is my view page code

<?php
      echo $this->Form->create('User');
      echo $this->Form->input('username', array('label' => 'Username'));
      echo $this->Form->input('email', array('label' => 'Email'));
      echo $this->Form->input('password', array('label' => 'Password'));
      echo $this->Form->submit('Sign Up');
      echo $this->Form->end();
?>

Here is my controller code

public function register() {
$this->layout = 'starter';
//debug($this->validationErrors);
if ($this->request->is('post')) {
    if ($this->User->validates()) {
        $this->User->save($this->request->data);
        $this->Session->setFlash(__('Please login your account'));
        $this->redirect('/users/login');
      } else {
        $this->Session->setFlash(__('The user could not be saved. Please, try again.'));
      }
 }
}

but validation message is not showing. What is wrong in my code?...

Upvotes: 0

Views: 183

Answers (3)

mark
mark

Reputation: 21743

Your code is wrong.

if ($this->request->is('post')) {
    if ($this->User->validates()) {
        $this->User->save($this->request->data);

this is not how it could ever work as the data is not passed prior to validation.

You need to first pass the data, then validate, then optionally save (or save and validate together):

if ($this->request->is('post')) {
    if ($this->User->save($this->request->data)) {}

or, careful not to retrigger validation twice:

if ($this->request->is('post')) {
    $this->User->set($this->request->data);
    if ($this->User->validates()) {
        $success = $this->User->save(null, array('validate' => false));

But that is documented.

The latter only makes sense if you really need to do this in two steps.

Upvotes: 1

iraqi_love4ever
iraqi_love4ever

Reputation: 583

Disable HTML5 required in your view page code

<?php
  echo $this->Form->create('User');
  echo $this->Form->input('username', array('label' => 'Username','required'=>'false'));
  echo $this->Form->input('email', array('label' => 'Email','required'=>'false'));
  echo $this->Form->input('password', array('label' => 'Password','required'=>'false'));
  echo $this->Form->submit('Sign Up');
  echo $this->Form->end();
?>

Upvotes: 0

Alimon Karim
Alimon Karim

Reputation: 4469

In your comment you have written you have changed layout page.It may you miss

<?php echo $this->Session->flash(); ?>

this line.Add this line in your view/layouts/yourlayout.ctp file.

Upvotes: 0

Related Questions