views:

637

answers:

1

Hi, Can anyone help me with a clear and complete example on how to set validations for 2 fields, say an email and password, with error messages?

From my understanding, the correct format is:

       var $validate = array(
               'password' => array(
                   'rule' => array('minLength', '8'),
                   'message' => 'Minimum 8 characters long'
                 ),
            'email_id' => array('email')
       );

but I can’t seem to get it work (show a message, or halt the execution of the action) in my tests.

Validations work fine but no way for the custom messages to appear!

EDIT

The validations and page redirections work fine now. Only the specific messages do not appear. That is, if I enter a password less than 8 characters, the message "minimum 8 characters needed" should appear immediately or after I click the register button. Is there any method to do this?

EDIT 2

My view file

  <!-- File: /app/views/forms/index.ctp  -->

   <?php 
  echo $javascript->link('prototype.js');
  echo $javascript->link('scriptaculous.js');
  echo $html->css('main.css');
?>

   <div id="register">
   <h3>Register</h3>
   <?php
  echo $form->create('User',array('action'=>'register'));
  echo $form->input('User.name');
  echo $form->input('User.email_id');
  echo $form->input('User.password');
  echo $form->end('Register');
    ?>
  </div>

  <div id="login">
  <h3>Login</h3>
  <?php
  echo $form->create('User',array('action'=>'login'));
  echo $form->input('User.email_id');
  echo $form->input('User.password');
  echo $form->end('Login');
   ?>
  </div>

Controller:

  <?php
  class UsersController extends AppController 
  {

var $name = 'Users';
var $uses=array('Form','User','Attribute','Result');
var $helpers=array('Html','Ajax','Javascript','Form');

function register()
{

 $userId=$this->User->registerUser($this->data);
 $this->User->data=$this->data;
     if (!$this->User->validates())
     {
      $this->Flash('Please enter valid inputs','/forms' );
      return; 
     }

     $this->Flash('User account created','/forms/homepage/'.$userId);            

}   

function login()
   {

 $userId=$this->User->loginUser($this->data);
 $this->User->data=$this->data;

 if (!$this->User->validates())
     {
      $this->Flash('Please enter valid inputs','/forms' );
      return; 
     }
 if($userId>0){
  $this->Flash('Login Successful');
  $this->redirect('/forms/homepage/'.$userId);
  break;

 }
 else{
  $this->flash('Username and password do not match.','/forms');

 }

}

}
?>

Model:

   <?php

   class User extends AppModel {
       var $name = 'User';
   var $components=array('Auth');
   var $validate = array(
   'name' => array(
             'rule'    => VALID_NOT_EMPTY,
             'message'  =>'Name cannot be null.'
            ),
   'password' => array(
      'rule' => array('minLength', '6'),
      'message' => 'Minimum 6 characters long.'
      ),
   'email_id' => array(
      'rule'=> array('email'),
      'message'=>'Invalid email.'
      )
       );

function registerUser($data)
{
 if (!empty($data)) 
 {
  $this->data['User']['name']=$data['User']['name'];
  $this->data['User']['email_id']=$data['User']['email_id']; 
  $this->data['User']['password']=$data['User']['password'];
  if($this->save($this->data))
  {
   $this->data['User']['id']= $this->find('all',array('fields' => array('User.id'),
        'order' => 'User.id DESC'   
        ));
   $userId=$this->data['User']['id'][0]['User']['id'];
   return $userId;
  }
 }
}

function loginUser($data)
{
 $this->data['User']['email_id']=$data['User']['email_id']; 
 $this->data['User']['password']=$data['User']['password'];   

 $login=$this->find('all');
 foreach($login as $form):
  if($this->data['User']['email_id']==$form['User']['email_id'] && $this->data['User']['password']==$form['User']['password'])
  {
   $this->data['User']['id']= $this->find('all',array('fields' => array('User.id'),
        'conditions'=>array('User.email_id'=> $this->data['User']['email_id'],'User.password'=>$this->data['User']['password'])  
        ));
   $userId=$this->data['User']['id'][0]['User']['id'];

   return $userId;

  }
 endforeach;
}
  }
 ?>
+4  A: 

Here is a live example from my project..

This is how you set up your validation in your model: Article model

Ignore the fact that I'm initializing the validate array from constructor, you can keep doing it like you're doing it now if you don't plan on implementing I18n and L10n.

Handling validation errors in controller: Articles controller

From line 266 to 280 you can see validation and save errors being handled with setFlash() + return.

That's pretty much all you need to do, just don't forget you need to use the FormHelper for your forms for the messages to work as expected.

Common error: you must not do a $this->redirect() after failed validation.

Hopefully this will set you on the right track :)

dr Hannibal Lecter
Now if I give the wrong input, It gets redirected to the page /users/register and displays the content as follows:Please correct the errors belowNot FoundError: The requested address '/users/register' was not found on this server.I dont get the specific error like,"Invalid email" or "Name Field should not be empty". And also How do I redirect it to the login page,if the invalid inputs are entered?
Angeline Aarthi
It sounds like you have a misconfigured Auth component which is preventing those specific error messages from appearing. You should really try commenting out parts of your code and check which bit is causing you trouble.
dr Hannibal Lecter
Do I need to have the Auth component for displaying those errors? I just cheched my components folder(inside app folder) and I do not have the auth.php file.
Angeline Aarthi
No, Auth is Cake built-in component. If the specific messages are not showing up, this probably means you're doing a redirect() somewhere. Can you post your code so we can check it out?
dr Hannibal Lecter
I've posted my entire code. The only place I do a redirect is When I check for the userId's value.if($userId>0){ $this->Flash('Login Successful'); $this->redirect('/forms/homepage/'.$userId); break; }If i try to redirect in the flash message itself, like $this->Flash('Login Successful','/forms/homepage/'.$userId), it isnt redirected to that page.If i dont use a redirect,how do i go to the homepage after the login is successful?
Angeline Aarthi
Hm....by the look of your code, it seems like your Flash() method is doing a redirect()? If it is, that's the cause..
dr Hannibal Lecter