Codeigniter form validation config file not working - codeigniter

I'm using the technique of saving codeigniter form validation rules to a config file as specified here, but can't seem to get it working.
I am also attempting to invoke validation callback functions from a Validation_Callbacks.php library which I'm autoloading via the autoload.php mechanism.
Below is a snippet from my form_validation.php form validation rules config file:
<?php
/* This config file contains the form validation sets used by the application */
$config = array(
'register_user' => array(
array(
'field' => 'dob',
'label' => 'lang:register_dob',
'rules' => 'trim|required|date_check|age_check|xss_clean'
), ...
)
)
And here is the Validation_Callbacks.php file, that lives under application/libraries:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* Custom validator library containing app-specific validation functions
*/
class Validation_Callbacks {
/* Checks that the given date string is formatted as expected */
function date_check($date) {
$ddmmyyyy='(0[1-9]|[12][0-9]|3[01])[- \/.](0[1-9]|1[012])[- \/.](19|20)[0-9]{2}';
if(preg_match("/$ddmmyyyy$/", $date)) {
return TRUE;
} else {
$this->form_validation->set_message('date_check', $this->lang->line('error_register_dob_format'));
return FALSE;
}
}
/* Checks that the given birthday belongs to someone older than 18 years old. We assume
* that the date_check method has already been run, and that the given date is in the
* expected format of dd/mm/yyyy */
function age_check($date) {
$piecesDate = explode('/', $date);
$piecesNow = array(date("d"), date("m"), date("Y"));
$jdDate = gregoriantojd($piecesDate[1], $piecesDate[0], $piecesDate[2]);
$jdNow = gregoriantojd($piecesNow[1], $piecesNow[0], $piecesNow[2]);
$dayDiff = $jdNow - $jdDate;
if ($dayDiff >= 6570) {
return TRUE;
} else {
$this->form_validation->set_message('age_check', $this->lang->line('error_register_age_check'));
return FALSE;
}
}
}
I'm invoking this using the standard:
if ($this->form_validation->run('register_user') == FALSE) {
My callback functions are not being called. Is there something I'm missing here? Thanks in advance for any help you may be able to provide!

Ensure that:
When a rule group is named identically
to a controller class/function it will
be used automatically when the run()
function is invoked from that
class/function.
To test you can try using:
$this->load->config('configname');

Related

problem (my_form_validation) not working properly for upload input

hoping someone can help me solve this problem, thanks a lot for providing the solution
i recently had a problem with my library called my_form_validation on codeigniter version 3. i don't know why it can enter validation true even though it was wrong in function photo check
I have done several options but none of the results I want. my example already used the callback it's the same
example code controller
public function validation_photo()
{
// load custom library Validation
$this->my_form_validation->config_photo();
$this->my_form_validation->photo_checker($_FILES['photo']);
// Conditional validation form
if ($this->form_validation->run() == FALSE) {
// does not pass validation
$data['Title'] = 'Profile';
$data['Content'] = 'management/V_Profile';
$this->load->view('dinamis/Layout', $data);
} else {
// passed validation
var_dump('passed');
}
}
the code above is my loading from my_form_validation library which works for configuring and validating the upload format
example code my_form_validation (config_photo)
function config_photo()
{
$ci = get_instance();
$config = array(
array(
'field' => 'photo',
'label' => 'photo',
'rules' => 'photo_checker',
),
);
$ci->form_validation->set_rules($config);
}
the code above is to set the rules to be used, I use photo_checker
example code my_form_validation (photo_checker)
function photo_checker($photo)
{
$ci = get_instance();
$allowed_mime_type_arr = array('image/jpeg', 'image/png', 'image/x-png', 'image/jpg');
$mime = $photo['type'];
if (in_array($mime, $allowed_mime_type_arr)) {
return TRUE;
} else {
$ci->form_validation->set_message('photo_checker', 'Please select a supported format (jpeg,png,jpg).');
return FALSE;
}
}
The above code is for validating if it doesn't match the desired format then it returns false with the message set
very very thank you very much for helping me.
I hope this issue gets resolved well in this forum, I'm sure there are really great people here

Using performAjaxValidation inside a widget (Yii)

I've created a widget with a CActiveForm in it. Everything works ok, but now i want to enable ajax validation for it.
The problem is that the output of my ajax validation is containing, besides the validation JSON string, all (well a part of it, since Yii::app()->end() stops the rest) of my html as well. Not weird, because i'm using it within a widget and the validation request is done to the controller/action where i've placed this widget on.
Is there some way to prevent outputting all the html, so a valid JSON string is returned?
I've already tried to set the validationUrl in the CActiveForm to another controller/action, but the problem is that i have to send the model with it and this model is determined in my widget and not on the validationUrl.
Widget:
public function run()
{
$model = new User;
$model->scenario = 'create';
$this->performAjaxValidation($model);
if (isset($_POST['User'])) {
$model->attributes = $_POST['User'];
if ($model->save()) {
}
}
$this->render('register-form', array(
'model' => $model
));
}
/**
* Performs the AJAX validation.
* #param User $model the model to be validated
*/
protected function performAjaxValidation($model)
{
if(isset($_POST['ajax']))
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
}
Output of performAjaxValidation() (the ajax call):
.. more html here ..
<section class="box">
<h1>Register form simple</h1>
{"UserPartialSignup_email":["Email is geen geldig emailadres."]}
I solved it this way:
I've created an AJAX controller where the validation is done:
AjaxController:
/**
* Validates a model.
*
* Validates a model, POST containing the data. This method is usually used for widget based forms.
*
* #param $m model name which have to be validated
* #param $s scenario for this model, optional.
* #return string JSON containing the validation data
*/
public function actionValidate($m, $s = null)
{
if ($this->checkValidationData($m, $s) && isset($_POST['ajax']))
{
$model = new $m;
$model->scenario = $s;
echo CActiveForm::validate($model);
Yii::app()->end();
} else {
throw new CHttpException(500, 'No valid validation combination used');
}
}
You can give the model name and a scenario as GET parameters with it, i'm checking if this combination is allowed by the checkValidationData() method.
In the view of my widget where the CActiveForm is placed, i've added the validationUrl, referring to ajax/validate:
widgets/views/registerform.php:
<?php $form = $this->beginWidget('CActiveForm', array(
'id'=>'signup-form-advanced',
'enableAjaxValidation'=>true,
'clientOptions' => array(
'validationUrl' => array('ajax/validate', 'm' => get_class($model), 's' => 'create')
)
//'enableClientValidation'=>true,
)); ?>

codeigniter config form_validation with subfolders not working

I have using a lot config form_validation file. It's working good!
But now I'm trying to get it work with controller in subfolder
/controllers/panel/users.php
My form_validation config file looks like
$config = array(
'panel/users/edit/' => array(
array('field' => 'login', 'label' => 'Логин', 'rules' => "trim|required|valid_email")
)
And my Users controller is
public function edit($user_id = FALSE)
{
if ($this->input->post('save'))
{
$this->load->library('form_validation');
if ($this->form_validation->run())
{
// Do some
}
}
}
But $this->form_validation->run() is always return FALSE
It isn't designed to work this way, there was a relevant change to ruri_string() #122 which would have fixed this but it had other repercussions and needs to be rethought.
You can call your validation rule group explicitly (drop the trailing slash from your rule group name)
if ($this->form_validation->run('panel/users/edit'))
or, if appropriate in your situation, workaround this by prepending uri->segment(1) to the auto-detected rule group.
application/libraries/MY_Form_validation.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Form_validation extends CI_Form_validation {
function run($group = '')
{
// Prepend URI to match subfolder controller validation rules
$uri = ($group == '') ? $this->CI->uri->segment(1) . $this->CI->uri->ruri_string() : $group;
return parent::run($uri);
}
}

codeigniter datamapper relationship validation issues

I need to set up the validation rules to validate the related items on a specific object, ie: A user can have no more than 3 products related to it.
I believe DataMapper can check for this validation using _related_max_size rule, but I can't figure out how to use it on the $validation array in the model.
So far I've tried this in both my user and product models:
var $validation = array(
'product' => array(
'rules' => array('max_size' => 3)
)
);
Can somebody show me an example on how to set up this at the model, controller and finally the view?
Edit: What I mean is, a user has many products, and can create a certain amount of them, let's say 3 products, when that amount is reached, the user can no longer create products, and this validation rule should not permit the user to create more products.
This would be the DB Schema:
Users table
------------------
id | username |
------------------
Products table
------------------------
id | user_id | name |
------------------------
More info here: http://codeigniter.com/forums/viewthread/178045/P500/
Thanks!
EDIT:
Ok, I got it all working now… Except, I need to do the following:
var $validation = array(
'product' => array(
'label' => 'productos',
'rules' => array('required','max_size' => $products_limit)
)
);
The $products_limit comes from the “plan” the user has associated, and it’s stored in the session when the user logs in. When I try to run this I get:
Parse error: syntax error, unexpected T_VARIABLE in /var/www/stocker/application/models/user.php on line 11
Is there any way to make this setting dynamic?
In model
var $validation = array(
array(
'field' => 'username',
'label' => 'Username',
'rules' => array('required')
)
);
In controller. $this -> $object = new Your_model();
$object->validate();
if ($object->valid)
{ $object->save();
// Validation Passed
}
else
{ $data['error'] = $object->error;
// Validation Failed
}
In view.
echo $error->field_name
I never use Codeigniter before, but give me a chance to help you. So far I didn't found any built-in validation in Code-igniter (correct me if I'm wrong).
One workaround that I could think of is to Callback:Your own Validation Functions. Below is a snip. Pardon me if it didn't work as you want.
In Model: (create something like)
function product_limit($id)
{
$this->db->where('product_id',$id);
$query = $this->db->get('products');
if ($query->num_rows() > 3){
return true;
}
else{
return false;
}
}
In controller: (create something like)
function productkey_limit($id)
{
$this->product_model->product_exists($id);
}
public function index()
{
$this->form_validation->set_rules('username', 'Username', 'callback_product_limit');
}
For more information Please refer to the manual page which gives more complete. I am also new to CodeIgniter. But I hope this helps you, not complicate you.
First, set up a custom validation rule in libraries/MY_Form_validation.php
If the file doesn't exist, create it.
Contents of MY_Form_validation.php:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Form_validation extends CI_Form_validation
{
function __construct($config = array())
{
parent::__construct($config);
}
function valid_num_products()
{
//Perhaps it would be better to store a maxProducts column in your users table. That way, every user can have a different max products? (just a thought). For now, let's be static.
$maxProducts = 3;
//The $this object is not available in libraries, you must request an instance of CI then, $this will be known as $CI...Yes the ampersand is correct, you want it by reference because it's huge.
$CI =& get_instance();
//Assumptions: You have stored logged in user details in the global data array & You have installed DataMapper + Set up your Product and User models.
$p = new Product();
$count = $p->where('user_id', $CI->data['user']['id'])->count();
if($count>=$maxProducts) return false;
else return true;
}
}
Next, set up your rule in config/form_validation.php.
Contents of form_validation.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
$config = array
(
'addProduct' => array
(
array
(
'field' => 'name',
'label' => 'Product Name',
'rules' => 'required|valid_num_products'
)
)
);
Next, set up your error message in language/english/form_validation_lang.php. Add the following line:
$lang['valid_num_products'] = "Sorry, you have exceeded your maximum number of allowable products.";
Now in the Controller, you'll want something along the lines of:
class Products extends MY_In_Controller
{
function __construct()
{
parent::__construct();
$this->load->library('form_validation');
}
function add()
{
$p = $this->input->post();
//was there even a post to the server?
if($p){
//yes there was a post to the server. run form validation.
if($this->form_validation->run('addProduct')){
//it's safe to add. grab the user, create the product and save the relationship.
$u = new User($this->data['user']['id']);
$x = new Product();
$x->name = $p['name'];
$x->save($u);
}
else{
//there was an error. should print the error message we wrote above.
echo validation_errors();
}
}
}
}
Finally, you might wonder why I've inherited from MY_In_Controller. There is an excellent article written by Phil Sturgeon over on his blog entitled Keeping It Dry. In the post he explains how to write controllers that inherit from access-controlling Controllers. By using this paradigm, controllers that inherit from MY_In_Controller can be assumed to be logged in, and the $this->data['user']['id'] stuff is therefore assumed to be available. In fact, $this->data['user']['id'] is SET in MY_In_Controller. This helps you seperate your logic in such a way that you're not checking for logged in status in the constructors of your controllers, or (even worse) in the functions of them.

how to use The gmail OpenInviter plugin in codeigniter

hi i am trying to use openinviter gmail plugin . i downloaded the gmail.plg.php from
http://debug.openinviter.com/download.php
i created a new project(not a codeigniter project) in xampp->htdocs->gmail when i tried to run the code it said .
Fatal error: Class 'openinviter_base' not found in C:\xampp\htdocs\gmail\gmail.plg.php on line 26
so i downloaded the openinviter_base.php and added to top of my gmail.plg.php now the problem is nothing shown , how can i integrate this , any one know how to use this plugin .
and also i need to use this plugin with codeigniter , i have no idea .
i also saw this code , but unable to get an idea
http://code.google.com/p/spherenetwork/source/browse/trunk/plugins/lcOpenInviterPlugin/lib/openInviter/openinviter_base.php?r=146
please help me , i tried very much but failed , thanks ....................................
The plug-ins are very coupled with the overall open inviter framework, so I just added basically the whole thing. Perhaps overkill, but nice if you want to add other plug-ins. I placed the entire inviter tree at the top level (probably not the best place). I then added the following lib into the libraries directory. This was taken off of one of the codeigniter forums. Both in code grabbed from the forum and the main openinviter scripts, i found I had to put in a fair amount of small tweaks.
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/* tky#tmo.blackberry.net inviter.php Fri May 22 04:00:19 GMT 2009 */
require_once($_SERVER['DOCUMENT_ROOT'].'/OpenInviter/openinviter.php');
class Importer
{
var $ci;
var $imported;
var $open_inviter;
var $plug_ins;
public function __construct()
{
$this->ci=&get_instance();
$this->open_inviter = new OpenInviter();
$this->plug_ins = $this->open_inviter->getPlugIns();
}
public function grab_contacts($plugin,$username,$password)
{
require_once($_SERVER['DOCUMENT_ROOT'].'/OpenInviter/openinviter.php');
$this->open_inviter->startPlugin($plugin);
if($this->open_inviter->login($username,$password))
{
$array = $this->open_inviter->getMyContacts();
if(is_array($array) && count($array)>=1)
{
$this->imported = $array;
//$this->_store_invited();
return($this->imported);
}
else
{
return $array;
}
}
else
{
//return 'ERROR on login.';
return false;
}
}
public function login($plugin,$username,$password)
{
$result = FALSE;
$this->open_inviter->startPlugin($plugin);
if($this->open_inviter->login($username,$password))
{
$result = TRUE;
}
return $result;
}
private function _store_invited()
{
foreach($this->imported as $mail=>$name)
{
$a = array
(
//'user_id' => ospc_user_id(),
'name' => $name,
'email_address' => $mail,
'status' => 0,
'time_imported' => time()
);
$this->ci->db->insert('ospc_imported',$a);
unset($a);
}
}
}
?>

Resources