Tutorials

Article Content:CodeIgniter Form Validation Callback function

CodeIgniter Form Validation Callback function

CodeIgniter Form Validation Callback function.

Validating your data is so important, you can't imagine any application without validation because it's the way you can control which data dealing with your application, it gives you this capability by filtering user input from crappy and useless inputs, and furthermore it will clean up inputs from hacking, spamming attempts.

For those reasons and because it was dangerous situation many programming groups, teams put their efforts and care about this matter, one of those people our CodeIgniter teams, so thanks guys for a good job.

Codeigniter had already a form validation rules that covers most cases you may face like

Email validation, Password validation, String and number validation…etc.

Note: For more details read this page on the official documentation

But in some specific circumstances you will need to be more accurate with data filtering, more customizable, and for those situations, CodeIgniter adds a callback function, also it is important to remember our tutorial  integrate recaptcha with codeigniter validation .

This is why then how to use the callback and how to create custom validation message?

 

Using CodeIgniter callback function

To understand callback function process correctly you should have a clear example, in order to do that we provide a contact us form as an example and we will practice step by step.

So to create custom callback functions in CodeIgniter you should follow these steps:

 

1-Create the HTML form
2-Create Codeigniter Custom validation callback function
3-Add Custom callback function in validation rules  

 

1- Create the HTML form

In this example, we will suppose you have a form with this inputs

A- Username:

Also use required to validate to not submit empty input.

B- User email:

In this input we utilize from email validate rule to validate it was email not anything else,

Here you will check username by trim and htmlspecialchars to validate it hasn't any spamming code, Create add function to handle the form

Note: as codeigniter guide says you should put callback function in the end of your validation rules.

C- User phone:

In this input you will check it is a phone number by using integer to validate it is numbers or mix of special characters and numbers, and not contains any alphabetical characters because there is no phone number has alphabetical characters, phone numbers usually been in such patterns

00947-567-66 or 0094756766

In addition, we add our callback function in the end to validate that user will submit phone number.

<form role="form" class="form-horizontal" action="<?= base_url() ?>contactus/send" method="post">
 <?php
if ($this->session->flashdata('success_msg')) {
echo "<p class='notice succeed'>" . $this->session->flashdata('success_msg') . "</p>";
                            }?>
  <div class="form-group">
  <input type="text" name="co_name" value="<?= set_value('co_name') ?>" class="form-control" placeholder="Name"/></div>
   <?php echo form_error('co_name'); ?>

<div class="form-group">
<input name="co_email" value="<?= set_value('co_email') ?>" type="email" class="form-control" placeholder="Email "/></div>


<div class="form-group">
<input  class="form-control" type="text"  name="co_phone"  placeholder=" Phone"/>
</div>
<?php echo form_error('co_title'); ?>

<button type="submit" class="btn btn-primary"> Send </button>
</form>

 

2-Create Codeigniter validation callback function

A- Create a callback validation function in the same controller

In our example, we will create it like this

    function  validate_phone_num($input){

        return ( ! preg_match("/^[0-9*#+]+$/", $input)) ? FALSE : TRUE;

}

 

Note: you may notice a parameter in a validation callback function, yeah this parameter is represented the input which sent by validation rule and you can use it directly.

 

Callback validation function recommended to be private like we do because no need to access it directly, but it should work correctly even if it was public.

This function is regex (aka regular expression) function to check that the user input is a number or special chars if yes it will return true else it will return false

 

3-Add Custom callback function in validation rules  

A- Put your check code in this function and return true if input's data passed your validation check or return true if input's data not passed

To use a callback you should put the method name in a rule, with “callback_” as a standard prefix from CodeIgniter, it will be like this:

 

$this->form_validation->set_rules('cj_phone', 'Phone' ,'trim|required|xss_clean|callback_validate_num|htmlspecialchars');

B- Put the custom validation message

Now after validating your input against regex function you can put the custom error message to the Send function, this message will trigger if callback function return False.

$this->form_validation->set_message('validate_num', 'The {field} doesn’t contain a correct phone number);

The full send function will be like this

function send()
    {
 $this->form_validation->set_rules('co_name', $this->lang->line('name'), 'trim|required|xss_clean|htmlspecialchars');
 $this->form_validation->set_rules('co_email',$this->lang->line('email'), 'trim|required|xss_clean|valid_email|htmlspecialchars');
 $this->form_validation->set_rules('co_phone', 'Phone' ,'trim|required|xss_clean|callback_validate_num|htmlspecialchars');
$this->form_validation->set_message('co_phone', 'The {field} doesn’t contain a correct phone number);


        if($this->form_validation->run()== false){

            $this->view('site/contactus');
        }else {

            $this->contactus->send();
            $data['msg'] = "Sent Successfully";
            $this->view('theme/msg2',$data);
        }
    }

But what if we want to use a function from another model in our application is this allowed, yes you can do it like this:

$this->form_validation->set_rules(
        'co_phone', 'Phone',
        array(
        'required',
        array($this->contact_model, 'valid_phone')
        )
);

 



Leave a Reply

Your email address will not be published.


Notify me of followup comments via e-mail.
You can also Subscribe without commenting.