Codeigniter build validation class at your own needs - php

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.

Related

How to set Error Messages for External Form Validation, CodeIgniter

I'm writing my own custom form validation class which extends from CI_Form_validation.
I'm curious how CodeIgniter sets its own form validation error messages. I don't see set_message in CI_Form_validation.
Let me know you need more clarification?
I think I got it. Will post the answer here in case someone else is asking...
Create a form_validation_lang.php inside the
application/language/english folder.
Then add a $lang associative array who index is the name of your
validation function prefixed with form_validation_. E.g. if
validation function is valid_date, it will look like this:
$lang['form_validation_valid_date'] = 'The {field} field must
contain a valid date.';
The lang file will be loaded automatically by CodeIgniter if you extend from CI_Form_validation.

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.

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!

Codeigniter form validation error message on custom function

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

url mapping in code igniter

I'm writing a PHP application using codeigniter framework. I'm trying to add a tool to download the data in the page as a .csv format file. I have the code to the server side, but I'm having trouble handling the URL mapping for the "Download" Controller.
in /controllers/ I have a controller called "Download", which is has a function called 'exportCSV', which receives a json object that is decoded and used to create the file. So, I'm trying to send a JavaScript array through 'post' to that method, but I'm having trouble handling the URL mapping.
here is my javascript call ...
function download(){
$.post('index.php/download/exportCSV', {input : dataForDownload.toString()},
function(answer){
alert(answer);
}
);
}
POST to index.php/download/exportcsv. CI doesn't much like Mixed Case controllers.
If you have a download controller, it should look like this:
class Download extends CI_Controller
{
function _construct()
{
parent::_construct();
}
function exportcsv()
{
if($this->input->post())
{
// Something was POSTed, continue
// process input
} else {
// Catch error if no POST
}
}
}
If you're getting a 404, your application might not be set up correctly. Check routes.php and your base_url.
I also recommend the CodeIgniter user guide. It's full of good information:
http://codeigniter.com/user_guide/overview/appflow.html
http://codeigniter.com/user_guide/overview/mvc.html

Categories