Hello i am building a REST API with CodeIgniter. The problemm is that i have set the validation rules but the code does not recognise them. I am using https://github.com/chriskacerguis/codeigniter-restserver.
The method put:https://github.com/alexmarton/RControl/blob/master/application/controllers/api.php and this example works. But in my case it does not.
public function properties_put(){
$property_to_update = $this->uri->segment(3);
$this->load->model('Model_properties');
$this->load->library('form_validation');
if (isset($property_to_update)) {
if (is_numeric($property_to_update)) {
$property_exist = $this->Model_properties->get_by(array('ID'=> $property_to_update));
if ($property_exist) {
$data = remove_unknown_fields($this->put(), $this->form_validation->get_field_names('property_put'));
$this->form_validation->set_data($data);
$debugdata = $this->form_validation->get_field_names('property_put');
foreach ($debugdata as $key => $value) {
log_message('debug', "Found validation data (".($key+1).")" . $value);
}
foreach ($data as $k => $val) {
log_message('debug', "Unknown field data (".($k+1).")" . $val);
}
if ($this->form_validation->run('property_put') != false) {
log_message('debug', "Passed validation data ");
}else{
$this->response(array("status" => "failure", "status_code" => "400", "response" => $this->form_validation->get_errors_as_array() ), REST_Controller::HTTP_BAD_REQUEST);
log_message('debug', "Error in validation data ");
}
} else {
$this->response(array("status" => "failure" , "status_code" => "404" , "message" => "Not Found", "response"=>"We couldn't find a property with the specified :id"), REST_Controller::HTTP_NOT_FOUND);
}
}
} else {
$this->response(array("status" => "failure" , "status_code" => "422" , "message" => "Unprocessable Entity", "response"=>"You have to specify the :id or the :name of the property that you would like to edit/update"), REST_Controller::HTTP_UNPROCESSABLE_ENTITY);
}
}
application/form_validation:
$config = array(
'price_post' => array(
array( 'field' => 'property_id', 'label' => 'Property id', 'rules' => 'trim|required' ),
array( 'field' => '_from', 'label' => 'Timeframe from', 'rules' => 'trim|required' ),
array( 'field' => '_to', 'label' => 'Timeframe to', 'rules' => 'trim|required' ),
array( 'field' => 'price', 'label' => 'Price', 'rules' => 'trim|required|integer|min_length[2]|is_natural_no_zero' ),
),
'availability_post' => array(
array( 'field' => 'property_id', 'label' => 'Property id', 'rules' => 'trim|required' ),
array( 'field' => '_from', 'label' => 'Timeframe from', 'rules' => 'trim|required' ),
array( 'field' => '_to', 'label' => 'Timeframe to', 'rules' => 'trim|required' ),
array( 'field' => 'free', 'label' => 'Is it free or not', 'rules' => 'trim|required|integer|numeric' )
),
'image_post' => array(
array( 'field' => 'property_id', 'label' => 'Property id', 'rules' => 'trim|required' ),
array( 'field' => 'url', 'label' => 'Url', 'rules' => 'trim|required|valid_url|prep_url' ),
array( 'field' => 'sort_order', 'label' => 'Sort Order', 'rules' => 'trim|required' )
),
'property_put' => array(
array( 'field' => 'name', 'label' => 'Property Name', 'rules' => 'trim|required' ),
array( 'field' => 'village', 'label' => 'Property Village', 'rules' => 'trim|required' ),
array( 'field' => 'town', 'label' => 'Property Town', 'rules' => 'trim|required' ),
array( 'field' => 'province', 'label' => 'Property Province', 'rules' => 'trim|required' ),
array( 'field' => 'region', 'label' => 'Property Region', 'rules' => 'trim|required' ),
array( 'field' => 'type', 'label' => 'Property Type', 'rules' => 'trim|required' )
)
);
application/helpers/my_api_helper:
function remove_unknown_fields($form_fields, $expected_fields){
$new_data = array();
foreach ($form_fields as $key => $value) {
if ($value != "" && in_array($key, array_values($expected_fields))) {
$new_data[$key] = $value;
}
}
return $new_data;
}
application/libraries/MY_Form_validation:
class MY_Form_validation extends CI_Form_validation {
function __construct($rules = array()) {
parent::__construct($rules);
$this->ci =& get_instance();
}
public function get_errors_as_array() {
return $this->_error_array;
}
public function get_config_rules() {
return $this->_config_rules;
}
public function get_field_names($form) {
$field_names = array();
$rules = $this->get_config_rules();
$rules = $rules[$form];
foreach ($rules as $index => $info) {
$field_names[] = $info['field'];
}
return $field_names;
}
}
The debug info:
DEBUG - 2016-05-31 18:34:25 --> Found validation data (1)name
DEBUG - 2016-05-31 18:34:25 --> Found validation data (2)village
DEBUG - 2016-05-31 18:34:25 --> Found validation data (3)town
DEBUG - 2016-05-31 18:34:25 --> Found validation data (4)province
DEBUG - 2016-05-31 18:34:25 --> Found validation data (5)region
DEBUG - 2016-05-31 18:34:25 --> Found validation data (6)type
DEBUG - 2016-05-31 18:34:25 --> Unable to find validation rules
and still it does not display errors when i do not post data. Anyone can help me understand what is going on?
What you have to do is this:
Modify the property_put method like this:
public function properties_put(){
$property_to_update = $this->uri->segment(3);
$this->load->model('Model_properties');
$this->load->library('form_validation');
if (isset($property_to_update)) {
if (is_numeric($property_to_update)) {
$property_exist = $this->Model_properties->get_by(array('ID'=> $property_to_update));
if ($property_exist) {
$property = $this->Model_properties->update_by('primary_field_key', $property_to_update, array(
'your_field_1' => $this->put('field_1'),
'your_field_2' => $this->put('field_2')
));
if($property){
//display correct response
} else {
//display wrong response
}
} else {
$this->response(array("status" => "failure" , "status_code" => "404" , "message" => "Not Found", "response"=>"We couldn't find a property with the specified :id"), REST_Controller::HTTP_NOT_FOUND);
}
}
} else {
$this->response(array("status" => "failure" , "status_code" => "422" , "message" => "Unprocessable Entity", "response"=>"You have to specify the :id or the :name of the property that you would like to edit/update"), REST_Controller::HTTP_UNPROCESSABLE_ENTITY);
}
}
In order for the above to work put data must have the following:
Header: Content-type: application/json
If you are using Postman you have to use raw as JSON like this
{
"field_1":"value 1",
"field_2":"value 2"
}
Hope it helps!!!
Related
I'm trying to do an email validation whereby the domain of the email would be #abc123.com. I've separated my form validation rules into another file in the application/config folder called form_validation.php. One of my rules consists of a callback_email_check.
Where should I put the function? In the main controller or together with the form_validation.php file where all my form validation rules are? I've tried putting at both options but at where I display my error message I'm getting an output saying Unable to access an error message corresponding to your field name Email.(email_check).
function email_check($email)
{
if( strpos($email, '#abc123.com') !== FALSE ) return TRUE;
$this->form_validation->set_message('email', 'Please use abc123 email only.');
return FALSE;
}
form_validation.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/* Form Validation Rules */
$config = array(
'login' => array(
array(
'field' => 'user_id',
'label' => 'User ID',
'rules' => 'trim|required'
),
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'trim|required'
)
),
'sign_up' => array(
array(
'field' => 'user_id',
'label' => 'User ID',
'rules' => 'trim|required'
),
array(
'field' => 'name',
'label' => 'Name',
'rules' => 'trim|required'
),
array(
'field' => 'email',
'label' => 'Email',
'rules' => 'trim|required|valid_email|callback_email_check'
),
array(
'field' => 'department',
'label' => 'Department',
'rules' => 'trim|required'
),
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'trim|required'
),
array(
'field' => 'cfm_password',
'label' => 'Re-type Password',
'rules' => 'trim|required|matches[password]'
)
),
'edit_profile' => array(
array(
'field' => 'new_password',
'label' => 'New Password',
'rules' => 'trim|required'
),
array(
'field' => 'retype_password',
'label' => 'Re-type Password',
'rules' => 'trim|required|matches[new_password]'
)
),
'forgot_password' => array(
array(
'field' => 'user_id',
'label' => 'User ID',
'rules' => 'trim|required'
),
array(
'field' => 'email',
'label' => 'Email',
'rules' => 'trim|required|valid_email|callback_email_check'
)
)
);
?>
On your function email_check, the set_message is not correct it should be the same name as the function.
Change this
$this->form_validation->set_message('email', 'Please use abc123 email only.');
To
$this->form_validation->set_message('email_check', 'Please use abc123 email only.');
Call backs http://www.codeigniter.com/userguide2/libraries/form_validation.html#callbacks
I am also facing the same problem and this is how i resolved it...
You can put email_check function in same controller. In case you are not getting the error message in callback then pass $this in your run()
if ($this->form_validation->run($this)) { ...}
and associating a Controller Method with a Rule Group -
$config = array(
'controller/method' => array(...));
view link for more : [associating a Controller Method with a Rule Group][1]
cheers !!
Just add this line in your config:
array(
'field' => 'email',
'label' => 'Email',
'rules' => 'trim|required|valid_email|callback_email_check',
**'errors' => array('email_check' => 'Your Error Message')**
),
Target
Mobile field is optional, and depending whether it has or has no value, there will be a validation rule to it, accordingly. But seems like, that even though the right validation rule is set, it always return true for the mobile field.
My Code
$client['mobile'] = "asdf";
$config = array(
'member_form' => array(
array( 'field' => 'client[firstName]', 'label' => 'First Name', 'rules' => 'required|trim'),
array( 'field' => 'client[lastName]', 'label' => 'Last Name', 'rules' => 'required|trim')
);
if($client["mobile"])
array_push($config["member_form"], array( 'field' => 'client[mobile]', 'label' => 'Mobile Number', 'rules' => 'required|trim|numeric'));
else
array_push($config["member_form"], array( 'field' => 'client[mobile]', 'label' => 'Mobile Number', 'rules' => 'trim'));
if ($this->form_validation->run("member_form") == TRUE) {
. . .
} else {
. . .
}
Thank you in advance.
I'd like some help please.
This is the array that holds all the validation on a contact form
class Contact_Form extends CI_Controller
{
private $_validation = array(
'fullname' => array(
'field' => 'fullname',
'label' => 'Fullname',
'rules' => 'trim|required|max_length[255]'
),
'email' => array(
'field' => 'email',
'label' => 'Email Address',
'rules' => 'trim|required|max_length[255]|valid_email'
),
'phone' => array(
'field' => 'phone',
'label' => 'Phone',
'rules' => 'trim|max_length[10]|integer'
),
'message' => array(
'field' => 'message',
'label' => 'Message',
'rules' => 'trim|required'
),
'captcha' => array(
'field' => 'captcha',
'label' => 'Security Code',
'rules' => 'trim|required|callback_validate_captcha'
)
);
// This is the part where I validate my contact form inside a method
$this->load->library('form_validation');
$this->form_validation->set_rules($this->_validation);
if ($this->form_validation->run() === true) {
echo 'works!';
}
This is the callback function that validates the captcha
public function callback_validate_captcha($str) {
$post_captcha = $this->input->post('captcha');
$set_captcha = $this->session->userdata('captcha');
if (strcmp($set_captcha, $post_captcha) !== 0) {
$this->form_validation->set_message('validate_captcha', '%s is wrong');
return false;
}
return true;
}
If i hit submit on an empty form I get the error that idicates that captcha is a required field, but if i submit a wrong code i don't get any error at all, which means that the callback is being ignored.
I tried to change my if statement
// change this (althought i feel its more correct)
if (strcmp($set_captcha, $post_captcha) !== 0)
// to this
if ($set_captcha != $post_captcha)
but the problem remains. Any ideas what's wrong?
you are making major mistake you have to make function validate_captcha instead of callback_validate_captcha.
Because callback is form keyword to call a function just try and bingo
i've set the validation rules in application/config/validation_rules.php and it looks like this
(short version)
$config = array(
'member/register' => array(
'field' => 'language',
'label' => 'language',
'rules' => 'required|min_length[5]|max_length[12]'
),
array(
'field' => 'email',
'label' => 'email',
'rules' => 'required|valid_email'
),
array(
'field' => 'password',
'label' => 'password',
'rules' => 'required|min_length[8]'
),
array(
'field' => 'verify_password',
'label' => 'password',
'rules' => 'required|min_length[8]|matches[password]'
));
and i'm calling it like this:
$this->config->load('validation_rules');
$this->form_validation->set_rules($config);
if($this->form_validation->run('member/register') == FALSE)
{
$page = array(
'meta_title' => 'member registration',
'load_page' => 'front/register_view'
);
$this->load->view('front/template', $page);
}
not only is the validation_errors() function not showing anything but i'm also getting this error:
Message: Undefined variable: config
update: (here is my controller)
class register extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->library('form_validation');
}
function index()
{
$this->config->load('validation_rules', TRUE);
$this->form_validation->set_rules($this->config->item('config', 'validation_rules'));
if($this->form_validation->run('member/register') == FALSE)
{
//validation doesnt pass, load view
$page = array(
'meta_title' => 'member registration',
'load_page' => 'front/register_view'
);
$this->load->view('front/template', $page);
}
else
{
$register_data = array(
'language' => $this->input->post('language'),
'email' => $this->input->post('email'),
'password' => md5($this->input->post('password')),
'fname' => $this->input->post('fname'),
'lname' => $this->input->post('lname'),
'phone' => $this->input->post('phone'),
'address' => $this->input->post('address'),
'address2' => $this->input->post('address2'),
'city' => $this->input->post('city'),
'state' => $this->input->post('state'),
'zipcode' => $this->input->post('zipcode'),
'gfname' => $this->input->post('gfname'),
'glname' => $this->input->post('glname'),
'gphone' => $this->input->post('gphone')
);
$this->session->set_userdata($register_data);
}
}
function package()
{
$page = array(
'meta_title' => 'Register Package',
'load_page' => 'register_package_view'
);
$this->load->view('includes/template', $page);
}
}
I encountered same problem but I managed to fix it by using following configuration:
In my application/config/form_validation.php:
$config = array(
"register" => array(
array(
"field" => "username",
"label" => "Username",
"rules" => "required"
)
)
);
Auto-load the custom config file "form_validation.php" inside application/config/autoload.php:
$autoload['config'] = array('form_validation');
In my controller:
// manually set rules by taking $config["register"] from form_validation.php
$this->form_validation->set_rules($this->config->item("register"));
// call run() without parameter
if ($this->form_validation->run() == FALSE) {
$this->load->view("user/register_test");
} else {
echo "Form content is correct";
}
I've tried calling the validator using $this->form_validation->run("register"), without using $this->form_validation->set_rules() function, but I got no luck. Setting the rules manually by retrieving it from config array in form_validation.php make my day.
In case you are extending the form_validation library, you need to pass the $config array to the parent constructor:
class MY_Form_validation extends CI_Form_validation {
/**
* constuctoooor
*/
function MY_Form_validation($config){
parent::__construct($config);
}
http://ellislab.com/forums/viewthread/181937/
It's also cleaner using the method outlined in the docs: http://ellislab.com/codeigniter%20/user-guide/libraries/form_validation.html#savingtoconfig to avoid calling $this->form_validation->set_rules(...);
/**
* This is the POST target for the password reset form above
* #return null
*/
public function submit(){
// perform validation //
if($this->form_validation->run() == FALSE){
// display error on sign-up page //
$this->session->set_flashdata("system_validation_errors", validation_errors());
redirect('member/forgot/password');
}
// more awesome code
}
$this->config->load('validation_rules');
$this->form_validation->set_rules($config);
should be:
$this->config->load('validation_rules', TRUE);
$this->form_validation->set_rules($this->config->item('validation_rules', 'validation_rules'));
Per the documentation:
// Loads a config file named blog_settings.php and assigns it to an index named "blog_settings"
$this->config->load('blog_settings', TRUE);
// Retrieve a config item named site_name contained within the blog_settings array
$site_name = $this->config->item('site_name', 'blog_settings');
Your rules are wrong, you forgot to put the validation group in an array:
$config['validation_rules'] = array(
'member/register' => array(
array(
'field' => 'language',
'label' => 'language',
'rules' => 'required|min_length[5]|max_length[12]'
),
array(
'field' => 'email',
'label' => 'email',
'rules' => 'required|valid_email'
),
array(
'field' => 'password',
'label' => 'password',
'rules' => 'required|min_length[8]'
),
array(
'field' => 'verify_password',
'label' => 'password',
'rules' => 'required|min_length[8]|matches[password]'
)
)
);
I have a controller and a view. I am trying to submit some details through a form, but when I submit it, no errors are displayed.
I am using only one controller to for 2 different types of users. The two users are -
User
Gym/Health Club Owner
And according to the $suertype, I have the same view being called but a different content being loaded.
This is my controller:
public function CreateProfile_Step2()
{
$data['page_title'] = 'Create Profile (Step 2)';
$loginid = $this->session->userdata('loginid');
$this->load->model('profilemodel', 'profile');
$userid = $this->profile->get_userid($loginid);
$this->session->set_userdata('userid', $userid);
$usertype = $this->profile->get_usertype($userid);
$data['usertype'] = $usertype;
if ($usertype == 'User') {
$this->load->model('activitymodel', 'activity');
$arr_activities = $this->activity->get_activities();
$data['options'] = $arr_activities;
}
else if ($usertype == 'Gym/Health Club Owner') {
$this->load->model('facilitymodel', 'facility');
$arr_facility = $this->facility->get_facilities();
$data['options'] = $arr_facility;
}
$config = array(
'User' => array(
array(
'name' => 'sex',
'label' => 'Sex',
'rules' => 'required'
)),
'Gym/Health Club Owner' => array(
array(
'name' => 'website',
'label' => 'Website',
'rules' => 'prep_url'
),
array(
'name' => 'hours_of_operation',
'label' => 'Hours of Operation',
'rules' => 'required|numeric'
),
array(
'name' => 'membership_charges',
'label' => 'Membership Charges',
'rules' => 'required|numeric'
))
);
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
$this->form_validation->set_rules($config);
if ($usertype == 'User') {
if ($this->form_validation->run('User') == FALSE) {
$this->load->view('create-profile-step-2', $data);
}
else {
$selected_options = $this->input->post('activities');
$this->activity->add_user_activities($userid, $selected_options);
$sex = $this->input->post('sex');
$this->profile->add_user_details($userid, $sex);
echo 'Profile Creation Completed!';
}
}
else {
if ($this->form_validation->run('Gym/Health Club Owner') == FALSE) {
$this->load->view('create-profile-step-2', $data);
}
else {
$selected_options = $this->input->post('facilities');
$this->facility->add_gym_facility($userid, $selected_options);
$website = $this->input->post('website');
$hours_of_operation = $this->input->post('hours_of_operation');
$membership_charges = $this->input->post('membership_charges');
$this->facility->add_gym_details($userid, $website, $hours_of_operation, $membership_charges);
echo 'Profile Creation Completed!';
}
}
}
This is my view:
<?php include 'user/inc/header.php'; ?>
<div id="content" class="row twelvecol">
<h1>Create Profile (Step 2 of 2)</h1>
<h2>For <?php echo $usertype; ?></h2>
<?php
echo form_open('register/CreateProfile_Step2');
if ($usertype == 'User') {
echo form_label('Sex', 'sex');
$options_sex = array(
'Male' => 'Male',
'Female' => 'Female'
);
echo form_dropdown('sex', $options_sex, 'male');
$ctr = 1;
echo form_label('Activities Interested In', 'activities');
foreach($options->result() as $option)
{
echo form_label($option->activity, 'activity-'.$ctr);
$arr_option = array(
'name' => 'activities[]',
'id' => 'activity-'.$ctr++,
'value' => $option->activity
);
echo form_checkbox($arr_option);
}
}
elseif ($usertype == 'Gym/Health Club Owner')
{
echo form_label('Website', 'website');
$arr_website = array(
'name' => 'website',
'id' => 'website',
'value' => set_value('website')
);
echo form_input($arr_website);
echo form_label('Hours of Operation', 'hours_of_operation');
$arr_hours = array(
'name' => 'hours_of_operation',
'id' => 'hours_of_operation',
'value' => set_value('hours_of_operation')
);
echo form_input($arr_hours);
echo form_label('Membership Charges', 'membership_charges');
$arr_charges = array(
'name' => 'membership_charges',
'id' => 'membership_charges',
'value' => set_value('membership_charges')
);
echo form_input($arr_charges);
$ctr = 1;
echo form_label('Facilities Available', 'facilities');
foreach($options->result() as $option)
{
echo form_label($option->facility, 'facility-'.$ctr);
$arr_option = array(
'name' => 'facilities[]',
'id' => 'facility-'.$ctr++,
'value' => $option->facility
);
echo form_checkbox($arr_option);
}
}
echo "<br/><br/>";
echo form_submit('submit', 'Create Profile');
echo form_close();
echo validation_errors();
?>
Return to previous step
</div>
<?php include 'user/inc/footer.php'; ?>
It's more likely some problem with the $config, because I have tried changing my code and used 2 separate controllers and views for the 2 cases.
Well, since no one answered my question. I was going through the code and found the errors myself. I had used the key 'name' in my configuration instead of 'field'.
INCORRECT CODE
$config = array(
'User' => array(
array(
'name' => 'sex',
'label' => 'Sex',
'rules' => 'required'
)),
'Gym/Health Club Owner' => array(
array(
'name' => 'website',
'label' => 'Website',
'rules' => 'prep_url'
),
array(
'name' => 'hours_of_operation',
'label' => 'Hours of Operation',
'rules' => 'required|numeric'
),
array(
'name' => 'membership_charges',
'label' => 'Membership Charges',
'rules' => 'required|numeric'
))
);
CORRECT CODE
$config = array(
'User' => array(
array(
'field' => 'sex',
'label' => 'Sex',
'rules' => 'required'
)),
'Gym/Health Club Owner' => array(
array(
'field' => 'website',
'label' => 'Website',
'rules' => 'prep_url'
),
array(
'field' => 'hours_of_operation',
'label' => 'Hours of Operation',
'rules' => 'required|numeric'
),
array(
'field' => 'membership_charges',
'label' => 'Membership Charges',
'rules' => 'required|numeric'
))
);