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

6 guaranteed steps how to create CRON JOB FUNTION in wordpress

Create Cron Job function in Wordpress plugin Step 1: Register function on plugin activate  register_activation_hook(__FILE__, 'activate_one'); Step 2: add_filter function for interval //Filter for Adding multiple intervals add_filter( 'cron_schedules', 'intervals_schedule' ); // define interval function   function intervals_schedule($schedules) {   $schedules['everyminute'] = array(    'interval' => 60, // Every 1 minutes    'display'  => __( 'Every 1 minutes' )   );   return $schedules;  } Step 3: Activate hook function   //Schedule a first action if it's not already scheduled   function activate_one() {   if (!wp_next_scheduled('wpyog_cron_action')) {    wp_schedule_event( time(), 'everyminute', 'wpyog_cron_action');   }  } Step 4: Cron hook function   //Hook into that action that'll fire after 1 minutes   add_action('wpyog_cron_action', 'execute_

How to Create a jQuery Autocomplete in Wordpress

How to Create a jquery-ui Autocomplete in wordpress. Autocomplete provides suggestions while you type into the text field. In Wordpress we fetch dynamically matched pattern. Include javascript and css files in header. Create action inside functions.php or inside plugin code. add_action('wp_head', 'custom_register_scripts'); function custom_register_scripts(){ wp_register_style( 'techsudhir_jquery_ui_css', plugin_dir_url(__FILE__) . 'css/jquery-ui.css', false,'1.0.0' ); wp_enqueue_style( 'techsudhir_jquery_ui_css' ); wp_register_script('techsudhir_jquery_ui_js',plugin_dir_url(__FILE__) . 'js/jquery-ui.js',array('jquery'),'1.1', false); wp_enqueue_script('techsudhir_jquery_ui_js'); wp_localize_script( 'techsudhir_autocomplete', 'jqueryAutocomplete', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) ); wp_enqueue_script( 'techsudhir_

Facebook Login

Step 1: Go on Apps & create new Apps Step 2: Enter the app name & choose category Step 3: Enter the site domain Script code <div id="fb-root"></div> <script   src="http://connect.facebook.net/en_US/all.js#appId=<?php echo '603609636351597';?>"> </script> <script>    FB.init({              appId:'<?php echo '603609636351597';?>', cookie:true,              status:true, xfbml:true           });   FB.getLoginStatus(function(response) {   }); Login function call on click function faceLogin(){  FB.login(function(response) {    if (response.authResponse) {  FB.api('/me', function(response) { $('input[id=facebook_login_fb]').val(response['id']); $('#fb_login_form').submit();  });    } else {  console.log('User cancelled login or did