Code Igniter - Form Validation (No Error Messages) - php

I'm having real trouble with Code Igniter. I have tried to enable errors which displays nothing useful and as far as I am aware, I am following the docs correctly. The problem I am having is that the validation_errors() function in the template does not echo validation problems. The validation process is working (it returns to the form if validation fails) however no error message is shown. Also, the set_values() function does not populate the fields with the information just entered and populates with the default value instead.
The tpl file is very basic and have the correct functions etc so that is not included (large), I have however included the method from the controller below.
// Setup Error Specifics
$this->form_validation->set_error_delimiters('<div class="nNote nFailure hideit"><p><strong>FAILURE: </strong>', '</p></div>');
$this->form_validation->set_rules('company_name', 'Company Name', 'required');
$this->form_validation->set_rules('telephone_no', 'Telephone Number', 'required|is_natural');
$this->form_validation->set_rules('email_address', 'Email Address', 'required|valid_email');
// Begin Validation
if($this->form_validation->run() === false) {
$data = array();
$data['company_info'] = $this->company_model->get_company($this->input->get('company_id'));
$this->load->view('common/header');
$this->load->view('company/edit', $data);
$this->load->view('common/footer');
} else {
$this->session->set_flashdata('success_message', 'You have updated the company record(s)');
redirect('customer/company/listing', 'location');
}
I appreciate your help,
Thanks!
UPDATE ---
After digging around the core of CodeIgniter, I've narrowed my search for the problem down to some hooks I am using. I have fully commented out the method code for each of the two hooks (both are post_controller_constructor hooks). Even with the code of each hook commented out, the form validation still fails. It appears (unless I'm heading down the wrong path) that post_controller_constructor hooks cause problems with form validation.
Any Ideas??

Ok fixed!!
The reason was unrelated to the code I was running and displaying on this question, it was related to how I had implemented the hooks in CodeIgniter. I had extended the core CI controller for the hook (which was the wrong thing to do). I have now modified the hook to use the get_instance() method of retrieving the CI instance and have managed to obviously achieve the same functionality from the hook without causing this issue.
So my fault!
Thanks for your help anyway!

Related

How to enable query builder for is_unique form validation in CodeIgniter?

I have a question about enabling the is_unique() rule for form validation in CodeIgniter.
In another explanation (link), they don't include the model query builder for standard usage of is_unique()
I need to use the rule is_unique(table.field) for my id field.
What should I do for making this function work on my model file to initiate table.field from my database? Because at documentation, I didn't see an explanation for enabling the is_unique rule.
My current code is still use matching data manually, but I need to know how to use this rules
$this->form_validation->set_rules('siteid', 'Site ID', 'trim|required|max_length[100]|is_unique[site_tower.site_id_tlp]');
I have just gone through the link you posted, There are 2 ways to use such validation. If you have set in your configuration files.
With that you can use the code as is is_unique[TABLE_NAME.FIELD] and it will work automatically. But at times this logic might not necessarily meet your need and you will need something more complex.
For example lets say you have a members registration that requires you to check if the email already exists, you can run is_unique and it will work perfectly. Now let's say you want to edit the same member, running is_unique on an edit function will render the user unable to save the data if no data is edited. WHY? because is_unique would determine that the email is already registered although it belongs to the current user that is being edited.
How do we fix this? We run our own callback in which we specify the logic.
You do it by specifying a method within the controller (or a model -- slightly different) but you prefix the method name with callback_ so that it is detected.
$this->form_validation->set_rules('username', 'Username', 'callback_username_check');
This will then look for a method in your controller called 'username_check'
public function username_check($str)
{
if ($str == 'test')
{
$this->form_validation->set_message('username_check', 'The {field} field can not be the word "test"');
return FALSE;
}
else
{
return TRUE;
}
}
Of course you can use a query within the callback to check against the db rather than check for just a string as it shows in the example.
more information can be found on Ci3 documentation.
LINK
Use CTRL + F and search for callback or is_unique
You might have missed this?
$this->load->library('database');
works instantly after adding database lib.

CodeIgniter's is_unique always saying value already exists

I'm using CodeIgniter's form validation, and I've spent a lot of time trying to fix this, with no luck.
I have this field:
<input type="text" name="user" id="user" length="20" placeholder="Username">
And I'm using this to validate:
$this->form_validation->set_rules('user', 'Username', 'trim|required|min_length[3]|max_length[20]|alpha_dash|is_unique[users.user]');
My db has a table users and user is a field in it, so I don't know what I'm doing wrong, or what the problem is. The table is empty (but I've also tried with it having records) and in phpmyadmin the "unique" icon is selected.
I know the db connection is working fine, because if I remove that rule and enter otherwise valid data and submit the form, then the user is added to the database.
Unless is_unique uses another db configuration file that I haven't configured? I don't really know. It's kind of frustrating and I'm thinking that I may as well just drop the use of a framework...
Your help would be great! Thanks.
This might/might not help: You seem to be loading the DB after running the form validation. There's also a typo uses.user.
In Transact-SQL the word "USER" is a special word. Try surrounding uses.user with a back-ticks like so: `users.user`...see if that helps.
try this :-
$this->form_validation->set_rules('user', 'Username', 'trim|required|min_length[3]|max_length[20]|alpha_dash|unique[users.user]');
it needs to load database.
$this->load->database();
I know your question is very old but I just recently encountered a similar problem with a custom form validation and after some serious debugging I found a cause and workaround.
Apparently, the CI core has a small bug: the database library isn't instanced (at least in the latest versions of CI) when calling the is_unique form validation method, thus preventing the check from actually being performed and always returning false as the validation result.
Here is the workaround for the form validation library (system/libraries/Form_validation.php)
public function is_unique($str, $field)
{
sscanf($field, '%[^.].%[^.]', $table, $field);
// add the following line
$this->CI->load->database();
return isset($this->CI->db)
? ($this->CI->db->limit(1)->get_where($table, array($field => $str))->num_rows() === 0)
: FALSE;
}
By adding the line after the comment, you'll make sure the database library is correctly instanced for the is_unique method and you'll get it to work. Without that line, the isset($this->CI->db) check will always return false
You could also put that line in the library's constructor, but then you'd be instancing the database library in all form validation rules which is not necessary (only is_unique needs it).
Using your code as an example, the is_unique validation rule works by looking for a field called user_name in your users database table. If the field with the same value exists it validates as false.
To make sure it runs only when the user submits a new value, you could check the posted value $this->input->post('user_name') against the value you pulled from the database to populate your form with. If they are the same, don't validate is_unique:
if($this->input->post('user_name') != $original_value) {
$is_unique = '|is_unique[users.user_name]'
} else {
$is_unique = ''
}
$this->form_validation->set_rules('user_name', 'User Name', 'required|trim|xss_clean'.$is_unique);

set custom validation messages for different fields in Codeigniter

I am working on already built codeigniter application. I am working on enhancements. One of the enhancement is to change the validation messages. So I checked the validation messages are drive through CI_Form_validation library in codeigniter. I want manage to set the custom messages using the "set_message".
$this->form_validation->set_message('required', 'Please enter %s.');
This is triggering for all fields where the values is empty. Which is good. But I have few select fields and radio buttons the application. For those message should change from "Please enter %s" to "Please select %s". I tried callback methods mentioned in the " How can I setup custom error messages for each form field in Codeigniter? "
And also I have tried the method mentioned in the following links
1) " https://github.com/EllisLab/CodeIgniter/wiki/Custom-Validation-Errors-per-Field ".
2) " http://www.witheringtree.com/2011/09/custom-codeigniter-validation-methods/ ".
Is there any way to set the different custom messages for different fields? If so please give me the suggestion. There is already a file called MY_Form_validation in the application (which is mentioned in the second link) with some custom functions. Custom validations are triggering in that file except the custom function written by me. (I know you think may be I have written an faulty code! But there is only simple echo statement in that function. Just for testing only I have put an echo statement).
You wouldn't be able to create a generic function to do this as codeigniter has no way of knowing how the information was posted as it just receives it as an array.
What you could do is create MY_Form_validation.php in application/libraries
class MY_Form_validation extends CI_Form_validation
{
public function required_select($val)
{
if ($this->required($val) === FALSE) {
$this->set_message('required_select', 'Please select %s');
return FALSE;
}
return TRUE;
}
}
then when creating the rules for form validation
$this->form_validation->set_rules('dropdown', 'Dropdown', 'required_select');
Obviously, replace dropdown with the name of the element.
Hope this helps!

GroceryCrud validation custom messages

I have one question.. How to validate fields data with custom error messages? I use codeigniter, and grocery crud with twitter bootstrap theme, and do some field required, for example:
$crud->set_rules('first_name', 'NAME', 'required'); OR $crud->required_fields('first_name');
Validation work fine, but if validation unsuccessfull - we see just alert with standart message - "An error has occurred on insert\update". How to display custom message that field are required or etc. ? Thanks.
Although this is old topic, but i thing someone can get this error as me just get it.
We can't use CI set_message function for CroceryCrud validation.
Because CroceryCrud use its validation object.
You can edit libraries/Grocery_CRUD.php, find line "protected function form_validation()",
at under this function, you can copy it, rename and edit access modifiler to public :
public function get_form_validation(){
if($this->form_validation === null)
{
$this->form_validation = new grocery_CRUD_Form_validation();
$ci = &get_instance();
$ci->load->library('form_validation');
$ci->form_validation = $this->form_validation;
}
return $this->form_validation;
}
Now, you can call it in your controller :
$crud-> get_form_validation()->set_message('check_city',"invail %s");
Take a look at function set_message in form_validation library:
http://ellislab.com/codeigniter/user-guide/libraries/form_validation.html#settingerrors

Why won't this Yii validator work?

Hi I'm trying to make my own Form validator just like the authenticate method in the LoginForm that is generated on the default configs.
public function rules()
{
return array(
// username and password are required
array('mnemonic, target_reg, source_reg', 'required'),
// rememberMe needs to be a boolean
array('target_reg_indirection, source_reg_indirection', 'boolean'),
array('mnemonic','foo'),
);
}
and here is the validator method:
public function foo($attribute,$params){
$this->addError('mnemonic', 'there was an error, you foo!');
}
it just doesn't work for me... notice how I added a rule that should not-work everytime. I just made it so I could see how it worked. But I never get to see the error message in my view. The default validators (like the one that checks for required fields) work.
Any ideas?
Because not all validators map to a client-side validator.
IN addition to that, I've created the code to handle ajax form validation and I've enabled ajaxValidation in my CActiveForm.
So now all works great. The validator I've created is working via ajax validation.
I had the same problem, in my case wasn't to enabled ajaxValidation, but the "safe" validator and a mix of other things.
Here I post some reading that helped me to solve the problem. Hope this will help others with the same problem.
I read a little bit about "safe" validator. (http://www.yiiframework.com/wiki/161/understanding-safe-validation-rules/)
I Understand the difference between AjaxValidation and ClientValidation. (http://www.yiiframework.com/doc/api/1.1/CActiveForm)
I created my own validator class. (search "custom validation yii" on google).

Categories