hzq hzq - 9 days ago 5
PHP Question

Callback function for form validation in config file

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'
)
)
);
?>

Answer

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

Comments