I'm using codeigniter 3, and I'm trying to use the form_validation library.
Basically, if validation fails, I'm catching the input data and then sending it back to the form.
So I'm sticking all form data in an array, like so:
// add input data to array
$org_data = array(
'org_id' => $this->input->post('org_id'),
'p_org_id' => $this->input->post('p_org_id'),
'account_ref' => $this->input->post('account_ref'),
'org_name' => $this->input->post('org_name'),
'address1' => $this->input->post('address1'),
'address2' => $this->input->post('address2'),
'address3' => $this->input->post('address3'),
'town' => $this->input->post('town'),
'county' => $this->input->post('county'),
'pcode' => $this->input->post('pcode'),
'phone' => $this->input->post('phone'),
'support_email' => $this->input->post('support_email'),
'notify_return' => $this->input->post('notify_return'),
'notify_email' => $this->input->post('notify_email'),
'email_interval' => $this->input->post('email_interval'),
'renewal_date' => $this->input->post('renewal_date'),
'login_reminder' => $this->input->post('login_reminder'),
'default_fireaware' => $this->input->post('default_fireaware'),
'open_training_url' => $this->input->post('open_training_url'),
);
All fine!
Now, to send the data back to the form, I am using the below.
$this->data['org_id'] = array(
'name' => 'org_id',
'id' => 'org_id',
'type' => 'text',
'value' => $this->form_validation->set_value('org_id'),
);
BUT
I don't want to create one of these for every input, so ideally I'd like to use a loop to create these. But I cant get it to work, I am getting undefined variable errors.
This is the loop in progress:
foreach($org_data as $key => $value){
$this->data['$key'] = array(
'name' => '$key',
'id' => '$key',
'type' => 'text',
'value' => $this->form_validation->set_value('$value'),
);
}
Can I use a loop to do this?
What are your thoughts?
use validation like this
$config = array(
array(
'field' => 'username',
'label' => 'Username',
'rules' => 'required'
),
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'required'
),
array(
'field' => 'passconf',
'label' => 'Password Confirmation',
'rules' => 'required'
),
array(
'field' => 'email',
'label' => 'Email',
'rules' => 'required'
)
);
$this->form_validation->set_rules($config);
if ($this->form_validation->run() == FALSE) {
$data['errors'] = validation_errors();
$this->load->view('yourview', $data);
} else {
$userData = $this->input->post();
$this->load->view('yourview', $data);
}
Basically, if validation fails, I'm catching the input data and then
sending it back to the form.
yeah i think this is the part to clarify - you don't need to do that at all -- thats the advantage of using set_value('fieldName'), it automatically echoes out the value. Same - on the form - with form_error( 'fieldName' ) it will display the field specific error message.
Related
I wonder what is the best and the most secured way of handling user's input in Codeigniter. Basically I have form for user's profile made by form helper like this:
echo form_open();
echo form_label($this->lang->line('user_update_profile_first_name'), 'first_name');
echo form_input(array('type' => 'text', 'name' => 'first_name', 'id' => 'first_name', 'maxlength' => '255', 'required' => 'true', 'value' => set_value('first_name', $user_profile['first_name'], false)));
echo form_label($this->lang->line('user_update_profile_last_name'), 'last_name');
echo form_input(array('type' => 'text', 'name' => 'last_name', 'id' => 'last_name', 'maxlength' => '255', 'required' => 'true', 'value' => set_value('last_name', $user_profile['last_name'], false)));
echo form_label($this->lang->line('user_update_profile_birth_date'), 'birth_date');
echo form_input(array('type' => 'text', 'name' => 'birth_date', 'id' => 'birth_date', 'maxlength' => '255', 'required' => 'true', 'value' => set_value('birth_date', $user_profile['birth_date'],
echo form_submit(array('value' => $this->lang->line('user_update_profile_form_submit'), 'name' => 'submit', 'class' => 'btn btn-primary'));
echo form_close();
As you can see in my code I am skipping xss filtering provided in set_value function due to xss filtering is done in form_input() already.
My Controller function for inserting data in DB looks like this
$validation_rules = array(
array(
'field' => 'first_name',
'label' => $this->lang->line('user_update_profile_validation_error_first_name'),
'rules' => 'required|trim|max_length[255]'
),
array(
'field' => 'last_name',
'label' => $this->lang->line('user_update_profile_validation_error_last_name'),
'rules' => 'required|trim|max_length[255]'
),
array(
'field' => 'birth_date',
'label' => $this->lang->line('user_update_profile_validation_error_birth_date'),
'rules' => 'required|trim|max_length[255]'
)
);
$this->form_validation->set_rules($validation_rules);
if($this->form_validation->run()) {
$user_data = array(
'user_id' => $this->profile_data->user_id,
'first_name' => $this->input->post('first_name', TRUE),
'last_name' => $this->input->post('last_name', TRUE),
'birth_date' => date('Y-m-d',strtotime($this->input->post('birth_date', TRUE)))
);
if($this->user_model->update_user_profile($user_data)) {
$view_data['success'] = TRUE;
$new_site_language = $this->language_model->getLanguageFolderById($user_data['site_language']);
$this->lang->load('application/user_lang', $new_site_language);
} else {
$view_data['server_error'] = TRUE;
}
}
I am filtering here data from user by provided $this->input->post('', true) xss filter. In model I am inserting data to DB by active record class. I am just wondering if this is the right and secure way of handling users input if there is not needed something like htmlspecialchars() . But what happens when someone have some "special" chars in name like for example Someone O'Sombody or some names from foreign countries? I am also showing data in navbar using html_escape($this->profile_data->first_name) to prevent running users potentially dangerous code. Did I get this whole "security thing" in the right way or there should be something changed because of potential danger?
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')**
),
I'm new to CodeIgniter (v 3.0.0) (coming from CakePHP), and I'm trying to set custom validation error messages to one of my forms. I'm using a config file to store all my validation rules, as explained here. This is my application/config/form_validation.php file:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
$config = array(
'appointments/signup' => array(
array(
'field' => 'admin[name]',
'label' => 'Name',
'rules' => 'required',
'errors' => array(
'required' => 'Please tell us your %s',
),
),
array(
'field' => 'admin[email]',
'label' => 'Email',
'rules' => 'required|valid_email|is_unique[users.email]',
'errors' => array(
'required' => 'Please enter your %s address',
'valid_email' => 'Please enter a valid email address',
'is_unique' => 'That email is already taken. Forgot your password?'
)
),
array(
'field' => 'admin[username]',
'label' => 'Username',
'rules' => 'required|min_length[4]|max_length[25]|is_unique[user_settings.username]',
'errors' => array(
'required' => 'Please choose a %s',
'min_length' => '%s must me at least 4 characters long',
'max_length' => '%s cannot exceen 25 characters',
'is_unique' => '%s is already taken :('
)
),
array(
'field' => 'admin[phone_number]',
'label' => 'Phone number',
'rules' => 'min_length[0]',
),
array(
'field' => 'admin[password]',
'label' => 'Password',
'rules' => 'required|min_length[8]',
'errors' => array(
'required' => 'Please choose a %s',
'min_length' => '%s must be at least 8 characters long'
)
),
array(
'field' => 'admin[passconf]',
'label' => 'Password',
'rules' => 'required|matches[admin[password]]',
'errors' => array(
'required' => 'Please re-type your %s',
'matches' => '%ss do not match'
)
),
array(
'field' => 'company[company_name]',
'label' => 'Organization\'s Name',
'rules' => 'required',
'errors' => array(
'required' => 'Please tell us your %s',
)
),
),
);
As you can see, I'm trying to set custom validation feedback using the errors array, as detailed here. But I still see the global default The <field name> field is required. message.
Is there a way to set custom validation messages in the config file, without having to edit the global default file?
Try to change the order of the keys in your array, something like this:
'appointments/signup' => array(
array(
'field' => 'admin[name]',
'label' => 'Name',
'errors' => array(
'required' => 'Please tell us your %s',
),
'rules' => 'required',
)
The exact same problem was happening to me, and after some debugging on the core classes, I was feeling stupid enough to try this.
Looks like a bug, but I didn't go any further.
I'm using version 3.0.1.
UPDATE
I was wrong, if this was happening on v 3.0.0, is not happening on 3.0.1. What I described above was me making a mistake with parentheses in my array.
Everything is working as it should.
validation error messages comes from language files because each language has own error messages
I think you can change validation error messages in language files.
Please try use helpers under application/helpers and define your validation errors in function. Then try accessing the validation rules or use errors under application/errors. please refer https://ellislab.com/codeigniter/user-guide/general/helpers.html
Firstly, make sure you are using Codeigniter 3 not any version of Codeigniter 2.x.x.
I was in trouble with the same issue and found that the errors array is available in Codeigniter 3 version and the config rules are set in form_validation's run() method, so if you see the set_rules function in Form_validation.php file you will see the 4th parameter which is errors
/**
* Set Rules
*
* This function takes an array of field names and validation
* rules as input, any custom error messages, validates the info,
* and stores it
*
* #param mixed $field
* #param string $label
* #param mixed $rules
* #param array $errors
* #return CI_Form_validation
*/
public function set_rules($field, $label = '', $rules = array(), $errors = array())
{
.....
And which is not available in 2.2-stable version, see Form_validation.php, and see the piece of code which shows the difference
/**
* Set Rules
*
* This function takes an array of field names and validation
* rules as input, validates the info, and stores it
*
* #access public
* #param mixed
* #param string
* #return void
*/
public function set_rules($field, $label = '', $rules = '')
{
....
May be you should put your key field within inverted commas like:
'field' => "admin['name']"
Do not try use direct call to signup(your_func_name).
$this->form_validation->run('signup')
Use alternate method - (controller_name/function_name)
$config = array(
'Authenticate_user/signup' => array(
array(
'field' => 'firstname',
'label' => 'Name',
'rules' => 'trim|required'
),
array(
'field' => 'useremail',
'label' => 'Email ID',
'rules' => 'trim|required|callback_check_unique_emailid'
),
array(
'field' => 'gender',
'label' => 'Gender',
'rules' => 'trim|required'
),
array(
'field' => 'age',
'label' => 'Age',
'rules' => 'trim|required'
),
array(
'field' => 'passcode',
'label' => 'Password',
'rules' => 'trim|required'
),
array(
'field' => 'confirmpasscode',
'label' => 'Confirm Password',
'rules' => 'required|matches[passcode]',
'errors' => array(
'matches[passcode]' => 'Only number is allowed'
)
),
array(
'field' => 'usertype',
'label' => 'User Type',
'rules' => 'trim|required'
),
array(
'field' => 'country',
'label' => 'Country',
'rules' => 'trim|required'
),
array(
'field' => 'state',
'label' => 'State',
'rules' => 'trim|required'
),
array(
'field' => 'category',
'label' => 'Category',
'rules' => 'required'
)
));
then call like it,
if ($this->form_validation->run() == FALSE) {... }
cheers!!!
I just created a form in cakephp and I would like to do a validation for one of the field.
The form will only be submitted if this particular field is left empty.
Here's a my particular field
<?php echo
$this->Form->input('MyForm.fieldA', array(
'type' => 'text',
'label' => '',
'class' => 'span3 detector-form',
))
?>
And my validation code:
public $validate = array(
'fieldA' => array(
'rule' => 'blank',
'on' => 'submit',
'message' => 'Failed authorize',
'last' => true
),
);
P/s. I tried using
public $validate = array(
'fieldA' => array(
'rule' => 'blank',
'on' => 'create',
'message' => 'Failed authorize',
'last' => true
),
);
But the 'create' sounds like only worked when the field is created.So I changed to 'submit' for a testing purpose.
I tried to use rule''=> 'Empty' as well but the validation doesn't work. Or is there any other alternative rules that I can use to reach this goal?
I am trying to validate a multiply select using input filter, but every time I see a error. The error is "notInArray":"The input was not found in the haystack".(I use ajax but it doesn`t metter).
I will show part of my code to be more clear.
in Controller:
if ($request->isPost()) {
$post = $request->getPost();
$form = new \Settings\Form\AddUserForm($roles);//
$form->get('positions')
->setOptions(
array('value_options'=> $post['positions']));
//.... more code...
When I put print_r($post['positions']); I see:
array(0 => 118, 1 => 119)
in ..../form/UserForm.php I create the multiply element
$this->add(array(
'type' => 'Zend\Form\Element\Select',
'attributes' => array(
'multiple' => 'multiple',
'id' => 'choosed_positions',
),
'required' => false,
'name' => 'positions',
));
and in the validation file the code is:
$inputFilter->add($factory->createInput(array(
'name' => 'positions',
'required' => false,
'validators' => array(
array(
'name' => 'InArray',
'options' => array(
'haystack' => array(118,119),
'messages' => array(
'notInArray' => 'Please select your position !'
),
),
),
),
What can be the reason every time to see this error, and how I can fix it?
By default selects have attached InArray validator in Zend Framework 2.
If you are adding new one - you will have two.
You should disable default one as follow:
$this->add(array(
'type' => 'Zend\Form\Element\Select',
'options' => array(
'disable_inarray_validator' => true, // <-- disable
),
'attributes' => array(
'multiple' => 'multiple',
'id' => 'choosed_positions',
),
'required' => false,
'name' => 'positions',
));
And you should get rid of the additional error message.
Please let us know if that would helped you.