Coding Cheatsheets - Learn web development code and tutorials for Software developers which will helps you in project. Get help on JavaScript, PHP, XML, and more.

Post Page Advertisement [Top]


Server Side Model Validation in cakephp

Step 1: Create a form in in view 
















View 
<div class="users form">
<?php echo $this->Form->create('User');?>
    <fieldset> 
<legend><?php echo __('Add User'); ?></legend>
        <?php echo $this->Form->input('username');
echo $this->Form->input('email');  echo $this->Form->input('password');
echo $this->Form->input('password_confirm', array('label' => 'Confirm Password *', 'maxLength' => 255, 'title' => 'Confirm password', 'type'=>'password'));
echo $this->Form->input('role', array(
'options' => array( 'king' => 'King', 'queen' => 'Queen', 'rook' => 'Rook', 'bishop' => 'Bishop', 'knight' => 'Knight', 'pawn' => 'Pawn') ));
echo $this->Form->submit('Add User', array('class' => 'form-submit',  'title' => 'Click here to add the user') ); ?>
    </fieldset>
<?php echo $this->Form->end(); ?>
</div>

Now the validation Code in Model:

public $validate = array(
        'username' => array(
'nonEmpty' => array('rule' => array('notEmpty'), 
'message' => 'A username is required',
'allowEmpty' => false),
'between' => array('rule' => array('between', 5, 15),
'required' => true, 'message' => 'Usernames must be between 5 to 15 characters'),
'unique' => array('rule'    => array('isUniqueUsername'),
                             'message' => 'This username is already in use'),
'alphaNumericDashUnderscore' => array('rule' => array('alphaNumericDashUnderscore'),
                             'message' => 'Username can only be letters, numbers and underscores'), ),
'password' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A password is required' ),
'min_length' => array(
'rule' => array('minLength', '6'), 
'message' => 'Password must have a mimimum of 6 characters')),
                  
'password_confirm' => array(
            'required' => array(
'rule' => array('notEmpty'),
'message' => 'Please confirm your password' ),
           'equaltofield' => array(
  'rule' => array('equaltofield','password'),
  'message' => 'Both passwords must match.') ),
                  
'email' => array(
'required' => array(
  'rule' => array('email', true),   
'message' => 'Please provide a valid email address.' ),
'unique' => array('rule'    => array('isUniqueEmail'),
 'message' => 'This email is already in use'),
'between' => array('rule' => array('between', 6, 60),
 'message' => 'Usernames must be between 6 to 60 characters')
                   ),
        'role' => array(
            'valid' => array(
                'rule' => array('inList', array('king', 'queen', 'bishop', 'rook', 'knight', 'pawn')),
                'message' => 'Please enter a valid role',
                'allowEmpty' => false
            )
        ),        
  'password_update' => array(
'min_length' => array(
 'rule' => array('minLength', '6'),  
 'message' => 'Password must have a mimimum of 6 characters',
 'allowEmpty' => true,
 'required' => false
)
        ),
  'password_confirm_update' => array(
 'equaltofield' => array(
 'rule' => array('equaltofield','password_update'),
 'message' => 'Both passwords must match.',
 'required' => false,
)
        )         
    );
         
                   /**
           * Before isUniqueUsername
           * @param array $options
           * @return boolean
           */
          function isUniqueUsername($check) {

                   $username = $this->find(
                             'first',
                             array(
                                      'fields' => array(
                                                'User.id',
                                                'User.username'
                                      ),
                                      'conditions' => array(
                                                'User.username' => $check['username']
                                      )
                             )
                   );

                   if(!empty($username)){
                             if($this->data[$this->alias]['id'] == $username['User']['id']){
                                      return true;
                             }else{
                                      return false;
                             }
                   }else{
                             return true;
                   }
    }

          /**
           * Before isUniqueEmail
           * @param array $options
           * @return boolean
           */
          function isUniqueEmail($check) {

                   $email = $this->find(
                             'first',
                             array(
                                      'fields' => array(
                                                'User.id'
                                      ),
                                      'conditions' => array(
                                                'User.email' => $check['email']
                                      )
                             )
                   );

                   if(!empty($email)){
                             if($this->data[$this->alias]['id'] == $email['User']['id']){
                                      return true;
                             }else{
                                      return false;
                             }
                   }else{
                             return true;
                   }
    }
         
          public function alphaNumericDashUnderscore($check) {
        // $data array is passed using the form field name as the key
        // have to extract the value to make the function generic
        $value = array_values($check);
        $value = $value[0];

        return preg_match('/^[a-zA-Z0-9_ \-]*$/', $value);
    }
public function equaltofield($check,$otherfield)
    {
        //get name of field
        $fname = '';
        foreach ($check as $key => $value){
            $fname = $key;
            break;
        }
        return $this->data[$this->name][$otherfield] === $this->data[$this->name][$fname];
    } } 

?>

If you want to validate file

var $validate = array(
   'name' => array(
                'notempty' => array(
                    'rule' => array('notempty'),
                    'message' => 'Enter File Name',
                ),
            ),
  'file_doc' => array(
   
   'file_docRule-1'=>array(
    'rule' => array('extension', array('doc', 'docx','txt', 'pdf', 'rtf','gif','jpg','jpeg','png','ppt','pptx','xls','xlsx','zip')),
    'message' => 'Upload file format is not correct.'
    ),
   'file_docRule-2'=>array(
    'rule' => array('attachmentMaxSize', 2097152),//1048576
    'message' => 'File cant be larger than 2MB.'
    ),
   'file_docRule-3'=>array(
    'rule' => array('checkUpload', true),
    'message' => 'Please select a file to upload.'
    ),
   )
 );

  function attachmentMaxSize($value, $max) {
$value = array_shift($value);
        if(!empty($value['tmp_name'])) {
            return (int)$value['size'] <= (int)$max;
        }
        return true;
    }
 function checkUpload($data, $required = false){
        $data = array_shift($data);
        if($data['size'] == 0){
   return false;
        }
        return true;

    }

In Controller put this code

$this->User->set($data); 
if($this->User->validates())
{

}else{   
$errors = $this->ModelName->validationErrors;
//or Retrieve the validation errors in an array:
errors = $this->ModelName->invalidFields(); 

}

How to validate checkbox

In Model

'agree' => array(
                'notEmpty' => array(
                    'rule'     => array('comparison', '!=', 0),
                    'required' => true,
                    'message'  => 'Please check this box if you want to proceed.'
                )
In view:


    <?php echo $this->Form->input('agree', array('type'=>'checkbox', 'label'=>__('I confirm I have read the <a href="/privacy-statement">privacy statement</a>.', true), 'hiddenField' => false, 'value' => '0')); ?

OR (In Model)

var $validate = array(
       'Roles' => array(
            'rule' => 'checkRoles',
            'message' => 'Please select atleast one role')
    ); 
public function checkRoles() {

        if (!empty($this->data["RolesModel"]["role"])) {
            return true;
        }

        return false;

    }
Note:

  • When you specify the CakePHP required attribute, what it really means is that this form field must always be present in the $this->data array.(i.e 'required' => true)
  • Use the "notEmpty" rule , if you really want to make sure a user has to enter data in a CakePHP form field.(i.e 'rule' => 'notEmpty').
  • You can  also use "allowEmpty" rule and set it to "false".(i.e 'allowEmpty'  => false,)



No comments:

Post a Comment

Bottom Ad [Post Page]