Skip to main content

Model Validation in Cakephp


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,)



Comments

Popular posts from this blog

A Guide to UTF-8 for PHP and MySQL

Data Encoding: A Guide to UTF-8 for PHP and MySQL As a MySQL or PHP developer, once you step beyond the comfortable confines of English-only character sets, you quickly find yourself entangled in the wonderfully wacky world of UTF-8. On a previous job, we began running into data encoding issues when displaying bios of artists from all over the world. It soon became apparent that there were problems with the stored data, as sometimes the data was correctly encoded and sometimes it was not. This led programmers to implement a hodge-podge of patches, sometimes with JavaScript, sometimes with HTML charset meta tags, sometimes with PHP, and soon. Soon, we ended up with a list of 600,000 artist bios with double- or triple encoded information, with data being stored in different ways depending on who programmed the feature or implemented the patch. A classical technical rat’s nest.Indeed, navigating through UTF-8 related data encoding issues can be a frustrating and hair-pul...

How To Create Shortcodes In WordPress

We can create own shortcode by using its predified hooks add_shortcode( 'hello-world', 'techsudhir_hello_world_shortcode' ); 1. Write the Shortcode Function Write a function with a unique name, which will execute the code you’d like the shortcode to trigger: function techsudhir_hello_world_shortcode() {    return 'Hello world!'; } Example: [hello-world] If we were to use this function normally, it would return Hello world! as a string 2. Shortcode function with parameters function techsudhir_hello_world_shortcode( $atts ) {    $a = shortcode_atts( array(       'name' => 'world'    ), $atts );    return 'Hello ' . $a['name'] . !'; } Example: [hello-world name="Sudhir"] You can also call shortcode function in PHP using do_shortcode function Example: do_shortcode('[hello-world]');

Integrating Kafka with Node.js

Integrating Kafka with Node.js Apache Kafka is a popular open-source distributed event streaming platform that uses publish & subscribe mechanism to stream the records(data). Kafka Terminologies Distributed system: Distributed system is a computing environment where various software components located on different machines (over multiple locations). All components coordinate together to get stuff done as one unit.   Kafka Broker: Brokers are cluster of multiple servers. Message of each topic are split among the various brokers. Brokers handle all requests from clients to write and read events. A Kafka cluster is simply a collection of one or more Kafka brokers. Topics: A topic is a stream of "related" messages. Its unique throughout application. Kafka producers write messages to topics. Producer: Producer publishes data on the topics. A producer sends a message to a broker and the broker receives and stores messages. Consumers: Consumers read data from topics. A consu...