I am trying to write Form validation rules in my Controller to submit Change Password form in which I am checking the old password too. I am getting the old password(current) from db and placing it in a hidden input field.
My Rules are simple and are given below
$config=array(
array(
'field' => 'old_password',
'label' => 'oldpass',
'rules' => 'trim|required'
),
array(
'field' => 'conf_password',
'label' => 'connewpass',
'rules' => 'trim|required|matches[password]'
),
array(
'field' => 'password',
'label' => 'newpass',
'rules' => 'trim|required'
)
My hidden input field in the form to save current password is like
<input type="hidden" name="old_pass" value="<?php echo $user['password']?>">
I know that matches(field name) in rules work for matching two field values but Where I am stuck is that the password coming from db is md5 encrypted. How can I encrypt the password coming from form and match with old pass field in the rule?
Setting Validation Rules CodeIgniter lets you set as many validation rules as you need for a given field, cascading them in order, and it even lets you prep and pre-process the field data at the same time. To set validation rules you will use the set_rules() method: $this->form_validation->set_rules();
PHP_EOL; $data['err'] = $err; $this->load->view('viewname', $data); } else if ($this->form_validation->run() == true ) { #code... } else.. after setting your custom message to $err variable, print it on your view. Save this answer.
There is no need of putting old password hash in hidden field. it's not even safe. you can create callback function for your own custom validation. Notice the comment i have did in following code.
$config=array(
array(
'field' => 'old_password',
'label' => 'oldpass',
'rules' => 'trim|required|callback_oldpassword_check' // Note: Notice added callback verifier.
),
array(
'field' => 'conf_password',
'label' => 'connewpass',
'rules' => 'trim|required|matches[password]'
),
array(
'field' => 'password',
'label' => 'newpass',
'rules' => 'trim|required'
)
In side your controller create a method as below
public function oldpassword_check($old_password){
$old_password_hash = md5($old_password);
$old_password_db_hash = $this->yourmodel->fetchPasswordHashFromDB();
if($old_password_hash != $old_password_db_hash)
{
$this->form_validation->set_message('oldpassword_check', 'Old password not match');
return FALSE;
}
return TRUE;
}
for more details of callback verification visit here
I have not verified above code. But hope you get the way to solve your problem.
Another approach:
if (!$this - > checkValidLogin($username, $old_password)) {
$this - > form_validation - > set_rules('password', 'Password', [
[
'old_password',
function($value) {
return false;
}
]
]);
$this - > form_validation - > set_message('old_password', 'Old password doesn\'t match.');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With