Codeigniter form validation in config depends on another input - php

I'm using Codeigniter form validation by config (not setting rules manually). What I need, is setting required rule depending on the other field. For example, Imagine we have the following rules:
'user' => array(
array(
'field' => 'user[phone]',
'rules' => 'required'
),
array(
'field' => 'user[email]',
),
array(
'field' => 'user[foo]',
//'rules' => 'required'
)
),
foo input must be required based on email field.
Note: It can be done with callback function, but it makes it a bit difficult in big applications. Any idea?

In your APPPATH.'config/form_validation.php' file set separated rule arrays
$config = array(
'yes_email' => array(
array(
'field' => 'user[phone]',
'rules' => 'required'
),
array(
'field' => 'user[email]',
),
array(
'field' => 'user[foo]',
'rules' => 'required'
)
),
'no_email' => array(
array(
'field' => 'user[phone]',
'rules' => 'required'
),
array(
'field' => 'user[email]',
),
array(
'field' => 'user[foo]',
)
),
);
, then in controller use what ever rule set you want. In example
if ($this->form_validation->run($rule) == FALSE) {
$this->load->view('myform');
} else {
$this->load->view('formsuccess');
}
Before this check, you should determine what rule you need there with something like:
$rule = 'no_email'; // set default value
switch($this->input->post('email')) {
case false:
break;
default:
$rule = 'yes_email'; // email has been posted / needed by app etc.
}
More in docs.

Related

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'
)
)
);
?>
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
I am also facing the same problem and this is how i resolved it...
You can put email_check function in same controller. In case you are not getting the error message in callback then pass $this in your run()
if ($this->form_validation->run($this)) { ...}
and associating a Controller Method with a Rule Group -
$config = array(
'controller/method' => array(...));
view link for more : [associating a Controller Method with a Rule Group][1]
cheers !!
Just add this line in your config:
array(
'field' => 'email',
'label' => 'Email',
'rules' => 'trim|required|valid_email|callback_email_check',
**'errors' => array('email_check' => 'Your Error Message')**
),

Codeigniter Form Validation Setting Strong Password Validation Rule In an Array

I am using codeigniter form validation to validate user data when creating new user. I want to add some sort of password criteria for example password must have
at least one capital letter, a number, and one of !, #, #, $ etc) and there have to be 6-25 characters.
This is the array that I am using for validation rules:
$config = array(
array(
'field' => 'title',
'label' => 'Title',
'rules' => 'trim|required'
),
array(
'field' => 'firstname',
'label' => 'First Name',
'rules' => 'trim|required|min_length[2]|max_length[100]|xss_clean'
),
array(
'field' => 'lastname',
'label' => 'Last Name',
'rules' => 'trim|required|min_length[2]|max_length[100]|xss_clean'
),
array(
'field' => 'phone',
'label' => 'Telephone',
'rules' => 'trim|required|intiger|min_length[11]|max_length[11]|xss_clean'
),
array(
'field' => 'email',
'label' => 'Email',
'rules' => 'trim|required|valid_email|is_unique[ci_user.email]|matches[conf_email]|xss_clean'
),
array(
'field' => 'conf_email',
'label' => 'Confirm Email',
'rules' => 'trim|required|valid_email|xss_clean'
),
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'trim|required|min_length[6]|max_length[25]|matches[conf_password]|xss_clean'
),
array(
'field' => 'conf_password',
'label' => 'Confirm Password',
'rules' => 'trim|required|xss_clean'
));
Can someone please guide me on how to achieve what I need. Thank you
you can setup call back function to check password strong validation. and call this function callback_is_password_strong in this line of your code.
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'trim|required|min_length[6]|max_length[25]|matches[conf_password]|xss_clean|callback_is_password_strong'
),
and if you look this function will return true or false and password array rule key is validated only when it returns true
public function is_password_strong($password)
{
if (preg_match('#[0-9]#', $password) && preg_match('#[a-zA-Z]#', $password)) {
return TRUE;
}
return FALSE;
}
Using callback function
public function check_strong_password($str)
{
if (preg_match('#[0-9]#', $str) && preg_match('#[a-zA-Z]#', $str)) {
return TRUE;
}
$this->form_validation->set_message('check_strong_password', 'The password field must be contains at least one letter and one digit.');
return FALSE;
}
Usage
$this->form_validation->set_rules('adminPassword', 'password', 'required|min_length[8]|max_length[25]|callback_check_strong_password');

Form Validation required either two fields or a third one

I've searched for a while around the internet and here on StackOverflow.
I've found similar needs, but I'm having a hard time adapting those solutions to my specific need.
I'm using CodeIgniter 2, and I've created a form.
I'm using form_validation to validate each values entered in the fields.
Now, I have 2 fields which are used for a period of time, and a third field used for a fileID.
The user must either fill [the period of time] fields, or the [fileID] field, or both.
$this->form_validation->set_rules('idx_start', 'lang:idx_start', 'trim');
$this->form_validation->set_rules('idx_end', 'lang:idx_end', 'trim');
$this->form_validation->set_rules('fileID', 'lang:fileID', 'trim');
I tried to look into Callbacks and create a custom validation rule but I can't seem to figure out an easy and efficient way for my need.
Thanks in advance for your help.
You could always create different rules arrays. I do this in a couple of projects.
So something like this in your controller:
if($condition1){
$rules = $this->my_model->rules1;
} else {
$rules = $this->my_model->rules2;
}
$this->form_validation->set_rules($rules);
And where $rules1 and $rules2 in 'my_model' would look something like this:
public $rules1 = array(
'idx_start' => array(
'field' => 'idx_start',
'label' => 'start',
'rules' => 'trim|required'
),
'idx_end' => array(
'field' => 'idx_end',
'label' => 'end',
'rules' => 'trim|required'
),
'fileID' => array(
'field' => 'fileID',
'label' => 'file id',
'rules' => 'trim'
)
);
public $rules2 = array(
'idx_start' => array(
'field' => 'idx_start',
'label' => 'start',
'rules' => 'trim'
),
'idx_end' => array(
'field' => 'idx_end',
'label' => 'end',
'rules' => 'trim'
),
'fileID' => array(
'field' => 'fileID',
'label' => 'file id',
'rules' => 'trim|required'
)
);
Or however they need to be. Hope this helps!
Probably there is better way, but this could work imho:
$this->form_validation->set_rules('fileID', 'lang:fileID', 'trim')
if ( $this->form_validation->run() != true ) {
$this->form_validation->set_rules('idx_start', 'lang:idx_start', 'trim');
$this->form_validation->set_rules('idx_end', 'lang:idx_end', 'trim');
}
if ( $this->form_validation->run() == false ) {
// form failed
} else {
// form passed
}
I've used following Add in to CodeIgniter for my specific need.
http://forum.codeigniter.com/thread-22443.html
Works fine for me.
Thanks

Custom validation error messages in CodeIgniter config file

I'm new to CodeIgniter (v 3.0.0) (coming from CakePHP), and I'm trying to set custom validation error messages to one of my forms. I'm using a config file to store all my validation rules, as explained here. This is my application/config/form_validation.php file:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
$config = array(
'appointments/signup' => array(
array(
'field' => 'admin[name]',
'label' => 'Name',
'rules' => 'required',
'errors' => array(
'required' => 'Please tell us your %s',
),
),
array(
'field' => 'admin[email]',
'label' => 'Email',
'rules' => 'required|valid_email|is_unique[users.email]',
'errors' => array(
'required' => 'Please enter your %s address',
'valid_email' => 'Please enter a valid email address',
'is_unique' => 'That email is already taken. Forgot your password?'
)
),
array(
'field' => 'admin[username]',
'label' => 'Username',
'rules' => 'required|min_length[4]|max_length[25]|is_unique[user_settings.username]',
'errors' => array(
'required' => 'Please choose a %s',
'min_length' => '%s must me at least 4 characters long',
'max_length' => '%s cannot exceen 25 characters',
'is_unique' => '%s is already taken :('
)
),
array(
'field' => 'admin[phone_number]',
'label' => 'Phone number',
'rules' => 'min_length[0]',
),
array(
'field' => 'admin[password]',
'label' => 'Password',
'rules' => 'required|min_length[8]',
'errors' => array(
'required' => 'Please choose a %s',
'min_length' => '%s must be at least 8 characters long'
)
),
array(
'field' => 'admin[passconf]',
'label' => 'Password',
'rules' => 'required|matches[admin[password]]',
'errors' => array(
'required' => 'Please re-type your %s',
'matches' => '%ss do not match'
)
),
array(
'field' => 'company[company_name]',
'label' => 'Organization\'s Name',
'rules' => 'required',
'errors' => array(
'required' => 'Please tell us your %s',
)
),
),
);
As you can see, I'm trying to set custom validation feedback using the errors array, as detailed here. But I still see the global default The <field name> field is required. message.
Is there a way to set custom validation messages in the config file, without having to edit the global default file?
Try to change the order of the keys in your array, something like this:
'appointments/signup' => array(
array(
'field' => 'admin[name]',
'label' => 'Name',
'errors' => array(
'required' => 'Please tell us your %s',
),
'rules' => 'required',
)
The exact same problem was happening to me, and after some debugging on the core classes, I was feeling stupid enough to try this.
Looks like a bug, but I didn't go any further.
I'm using version 3.0.1.
UPDATE
I was wrong, if this was happening on v 3.0.0, is not happening on 3.0.1. What I described above was me making a mistake with parentheses in my array.
Everything is working as it should.
validation error messages comes from language files because each language has own error messages
I think you can change validation error messages in language files.
Please try use helpers under application/helpers and define your validation errors in function. Then try accessing the validation rules or use errors under application/errors. please refer https://ellislab.com/codeigniter/user-guide/general/helpers.html
Firstly, make sure you are using Codeigniter 3 not any version of Codeigniter 2.x.x.
I was in trouble with the same issue and found that the errors array is available in Codeigniter 3 version and the config rules are set in form_validation's run() method, so if you see the set_rules function in Form_validation.php file you will see the 4th parameter which is errors
/**
* Set Rules
*
* This function takes an array of field names and validation
* rules as input, any custom error messages, validates the info,
* and stores it
*
* #param mixed $field
* #param string $label
* #param mixed $rules
* #param array $errors
* #return CI_Form_validation
*/
public function set_rules($field, $label = '', $rules = array(), $errors = array())
{
.....
And which is not available in 2.2-stable version, see Form_validation.php, and see the piece of code which shows the difference
/**
* Set Rules
*
* This function takes an array of field names and validation
* rules as input, validates the info, and stores it
*
* #access public
* #param mixed
* #param string
* #return void
*/
public function set_rules($field, $label = '', $rules = '')
{
....
May be you should put your key field within inverted commas like:
'field' => "admin['name']"
Do not try use direct call to signup(your_func_name).
$this->form_validation->run('signup')
Use alternate method - (controller_name/function_name)
$config = array(
'Authenticate_user/signup' => array(
array(
'field' => 'firstname',
'label' => 'Name',
'rules' => 'trim|required'
),
array(
'field' => 'useremail',
'label' => 'Email ID',
'rules' => 'trim|required|callback_check_unique_emailid'
),
array(
'field' => 'gender',
'label' => 'Gender',
'rules' => 'trim|required'
),
array(
'field' => 'age',
'label' => 'Age',
'rules' => 'trim|required'
),
array(
'field' => 'passcode',
'label' => 'Password',
'rules' => 'trim|required'
),
array(
'field' => 'confirmpasscode',
'label' => 'Confirm Password',
'rules' => 'required|matches[passcode]',
'errors' => array(
'matches[passcode]' => 'Only number is allowed'
)
),
array(
'field' => 'usertype',
'label' => 'User Type',
'rules' => 'trim|required'
),
array(
'field' => 'country',
'label' => 'Country',
'rules' => 'trim|required'
),
array(
'field' => 'state',
'label' => 'State',
'rules' => 'trim|required'
),
array(
'field' => 'category',
'label' => 'Category',
'rules' => 'required'
)
));
then call like it,
if ($this->form_validation->run() == FALSE) {... }
cheers!!!

How I set the inputFilter to not allow white space in zend framework 2?

How I set the inputFilter to not allow white space in zend framework 2?
I'm trying this:
$inputFilter->add($factory->createInput(array(
'name' => 'codigo',
'required' => true,
'validators' => array(
array(
'name' => 'not_empty',
),
),
'filters' => array(
array(
'name' => 'Alnum',
'allowwhitespace' => false,
),
),
)));
Few points in your code needs minor tweaks;
ValidatorPluginManager uses normalized aliases to invoke
validators by cannonical names, which means 'not_empty' is not a
valid alias, it should be 'notempty' or 'NotEmpty'.
Also your Alnum filter signature seems invalid. You should
provide additional options inside the options sub key with underscores. (Yes, this is really weird inconsistency)
Try this:
$filter = new \Zend\InputFilter\InputFilter();
$filter->add(array(
'name' => 'codigo',
'required' => true,
'validators' => array(
array(
'name' => 'NotEmpty',
),
),
'filters' => array(
array(
'name' => 'Alnum',
'options' => array(
'allow_white_space' => false,
)
),
),
));
$filter->setData(['codigo' => 'Whitespace exists']);
if($filter->isValid() === false) {
// You'll fall here with a value like multiple spaces etc..
var_dump($filter->getMessages());
} else {
var_dump($filter->getValues()); // Prints ['codigo' => string 'Whitespaceexists']
}

Categories