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
Related
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.
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!
I made a custom function for my form validation in Codeigniter.
Its hooked to the URL Helper, i achieved this by making a MY_url_helper.
The helper modification:
function valid_url($str) {
$pattern = "/^(http|https):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i";
if (preg_match($pattern, $str)) return TRUE;
else return FALSE;
}
/* End of file MY_url_helper.php */
/* Location: ./application/helpers/MY_url_helper.php */
How i call the validation:
$this->form_validation->set_rules('image', 'Image path', 'valid_url');
The language file:
$lang['valid_url'] = "The %s field must contain a valid URL.";
/* End of file form_validation_lang.php */
/* Location: ./system/language/english/form_validation_lang.php */
But it doesn't show any error message when submitting the form.
If i change the valid_url function to echo something on true and false, it will execute that. So it runs the function.
How can i make the error message appear?
Are you printing validation errors to your view? Add this line above your form in your view and see if it prints then.
<?php echo validation_errors(); ?>
Edit:
A few things based on your reply...I've never actually used a "helper" function as a callback for validation...I've always defined the callback in the controller where the validation occurs. Someone else may be able to elaborate on whether you can use a helper function as a callback. You may have to declare your validation function in the controller. You could also return the helper function from a callback you declare in the controller as well to keep from having to re-write your helper in two places. That may work.
I assume you are loading the 'url' helper in your controller?
Also..per CodeIgniter's documentation...I believe you are supposed to append 'callback_' to the beginning of your function name in your 'set_rules' declaration.
$this->form_validation->set_rules('image', 'Image path', 'callback_valid_url');
http://ellislab.com/codeigniter/user-guide/libraries/form_validation.html#callbacks
I am working in codeigniter and Iam looking to make my own custom validation class using "Validation_form" library and my custom rule where I will place my own validation rules and use that from everywhere in my project, but this seems impossible, I tried in couples ways to handle this but nothing.
Codeigniter kindle force me to make my callback methods in my controller but I need them in my library or "method" or wherever else!!!
My question is, can I build an specific library where I'll place my validation rules and other functions I need to handle that?
you could create a new library in application/libriries and name the file MY_Form_validation
What you are doing here is extending the form_validation class so that you will not need to mess with the core files.
The MY_ is what is set on your config, be sure to check it if you changed yours.
sample MY_Form_validation.php
class MY_Form_validation Extends CI_Form_validation
{
//this is mandatory for this class
//do not forget this or it will not work
public function __construct($rules = array(){
parent::__construct($rules);
$this->CI->lang->load('MY_form_validation');
}
public function method1($str){
return $str == '' ? FALSE : TRUE;
}
pulic function method2($str)
{
//if you want a validation from database
//you can load it here
// or check the `form_validation` file on `system/libraries/form_validation`
}
public function check_something_with_post($tr)
{
return $this->CI->input->post('some_post') == FALSE ? FALSE : TRUE;
}
}
Basically, when you call a rule sample method1|method2 the value of your post field will be the parameter of the method. if you want to check other post you can do it by using $this->CI->input->post('name of the post');
when you want to pass a parameter just look at the form validation is_unique or unique code on system/libraries/form_validation you will have an idea.
To create a error message that goes with it go to application/language/english/MY_Form_validation_lang
Sample MY_form_validation_lang.php
$lang['method1'] = "error error error.";
$lang['method2'] = "this is an error message.";
if english does not exist on your application/language just create it.
check more atCreating libraries
NOTE:
On some linux or debian server you may want to change the file name from MY_Form_validation to
MY_form_validation note the small f on the word form.
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!