Hello all, this is my first CI project.
I have a simple form validation function in my model.
function verify_login()
{
//This method will have the credentials validation
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');
var_dump($this->form_validation->run());
die;
if ($this->form_validation->run() == FALSE) {
//Field validation failed. User redirected to login page
$this->load->view('login_view');
} else {
//Go to private area
redirect('home', 'refresh');
}
}
This only works when it's in a controller but not in a model. When I try passing the variables from the controller to the function in the model, the variables get received but won't process.
Can someone enlighten me? Thank you.
its fine to do your form validation in a model. But you want to have the validation return True or False to your controller. Not call a view. So like
// in your Model lets call it Users
function verify_login()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');
if ($this->form_validation->run() == FALSE) {
return FALSE ;
} else {
return TRUE;
}
}
// Your callback function
// in Controller
function verify(){
if( $this->users->verify_login() == FALSE ){
// $this->errormessage will be available in any view that is called from this controller
$this-errormessage = "There was an error with your Log In. Please try again." ;
$this->showLogin() ; }
else {
// set a session so you can confirm they are logged in on other pages
$this->setLoginSession($this->input->post('username', TRUE)) ;
$this->showUserHome(); }
}
Another thing to think about -- often people know their user name but mess up their password. So if you check for them separately you can adjust the error message accordingly. And if you check for user name and there are no results -- you don't need to check for password and in the error message you can tell them there is no user by that name.
My biggest recommendation to you is to not do validations like this in your model. If you're validating in your model it needs to be against a database value directly and not a form.
Please let me know if that solves your problem, if not please comment and I'll edit my answer.
UPDATE: Please ignore some of the above, as I was going off theory and not fact :)
I'll have to dig deeper into the CI core to get a good idea of what's wrong with this. Your code itself looks ok. Only thing I can see is that your callback may not exist in your model and only in your controller. Echoing the below I do not consider this a good use of the model.
The docs on validations
class Data_model extends CI_Model
{
public function rules()
{
return [
['field' => 'pertanyaan',
'label' => 'pertanyaan',
'rules' => 'required|is_unique[data.pertanyaan]'],
['field' => 'jawaban',
'label' => 'jawaban',
'rules' => 'required']
];
}
}
class Datas extends CI_Controller
{
public function add()
{
$data = $this->data_model;
$validation = $this->form_validation;
$validation->set_rules($data->rules());
if ($validation->run()) {
$data->save();
$this->session->set_flashdata('success', 'Berhasil disimpan');
}
$this->load->view("admin/data/new_form");
}
}
Related
I'm developing a function that should enable users to update their personal information and I'm using CI form validation library. I'd want to know if what I'm doing is right.
public function updateDetails()
{
$this->load->model('users_model'); // load users model
$username = $this->input->post("username", true); // get the post from view
$this->form_validation->set_rules('username', 'Username', 'required|max_length[32]');
if($this->form_validation->run() === true)
{
// Send to model
}
}
Is this right? Or is there another method to do this?
yes so far you're right
but you should process if the validation is successful
public function updateDetails()
{
// load the library if not already loaded in config/autoload.php
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'required|max_length[32]');
if($this->form_validation->run() === true)
{
$this->load->model('users_model'); // load users model
$username = $this->input->post("username", true); // get the post from view
// Send to model
}
else
{
$data['error_message'] = "form not valid ...blablabla";
//go back to form
$this->load->view("form_vew",$data);
}
}
I have checked all the possible things that might go wrong with my code but still it showing me this error. Please help .
Unable to access an error message corresponding to your field name Username.(check_username)
And this is my code below:
public function index()
{
if ( ! file_exists(APPPATH.'/views/login.php'))
{
/* Whoops, we don't have a page for that! */
show_404();
}
$this->load->helper('security');
$this->load->library('form_validation'); // Including Validation Library.
$this->form_validation->set_error_delimiters('<div class="error">', '</div>'); // Displaying Errors in Div
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean|callback_check_username'); // Validation for Username Field
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean'); // Validation for Password field.
if ($this->form_validation->run() == FALSE) {
$this->load->view('login');
}
function check_username($username)
{
if ($username == 'test') {
$this->form_validation->set_message('check_username','already exists.');
return false;
} else {
return TRUE;
}
}
}
Do $config['global_xss_filtering'] = TRUE; in config file.
in Codeigniter-3 xss_filtering is not a part of form_validation.
You have to add the validation language in the system folder. Check the video
https://www.google.co.in/url?sa=t&rct=j&q=&esrc=s&source=web&cd=6&cad=rja&uact=8&sqi=2&ved=0ahUKEwi71dGkn73MAhVBQI4KHeZJC2gQtwIIPTAF&url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D56EDSocDhjk&usg=AFQjCNE_nhBpNwUOz9nkrcRYYgL50p34Kw&sig2=PSUISbtldDaWWdTyKJ6CPw&bvm=bv.121070826,d.c2E
<?php
class Form extends CI_Controller {
public function index()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
$this->form_validation->set_rules('password', 'Password', 'required');
$this->form_validation->set_rules('confpassword', 'Password', 'required|matches[password]', 'callback__matcherror');
//$this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
//$this->form_validation->set_rules('email', 'Email', 'required');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('login');
}
else
{
$this->load->view('insert_dream');
}
}
public function _matcherror() {
$this->form_validation->set_message('_matcherror', 'Passwords should match');
return FALSE;
}
}
?>
i am a newbie to codeigniter. The above code doesnt display passwords should match error message. Is something wrong with the callback or Am i missing something.
Take a look here. You don't need to make a callback.
You are passing callback__matcherror as fourth parameter of set_rules function.It should be 3rd parameter. Use this way
$this->form_validation->set_rules('confpassword', 'Password', 'required|matches[password]|callback__matcherror');
Note
You will get this error message if your password fields match.Because you applying 3 rule there.3rd rule(call_back_function) will apply when 2nd rule is success. Your 2nd rule will valid when passwords matches.
matches[password]
will automatically check for password. You need not to use callback function callback__matcherror
I am trying to use CodeIgniter's form validation class. I've used the "valid_email" parameter, as can be seen from the code below, but even when an invalid email address is entered it still passes the validation check. I tested with the string: testing123
public function login()
{
$this->form_validation->set_rules('authEmail', 'trim|required|valid_email|xss_clean');
$this->form_validation->set_rules('authPassword', 'trim|required');
$email = $this->input->post('authEmail');
$password = $this->input->post('authPassword');
if($this->form_validation->run() === FALSE) {
$this->session->set_flashdata('formValidationError', validation_errors('<p class="error">', '</p>'));
redirect('/');
} else {
// Begin authentication
}
}
Anyone have any idea what I'm doing wrong or if this is a CodeIgniter issue?
To note, I am setting a flashdata session as opposed to using:
<?php echo validation_errors(); ?>
... this is because I am doing a redirect back to the homepage (which is the login page as it's a private site).
Try this:
public function login()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('authEmail', 'Email', 'trim|required|valid_email|xss_clean');
$this->form_validation->set_rules('authPassword', 'Password', 'trim|required');
if($this->form_validation->run() !== false){
//validation passed
$email = $this->input->post('authEmail');
$password = $this->input->post('authPassword');
// Begin authentication
}
else {
$this->session->set_flashdata('formValidationError', validation_errors('<p class="error">', '</p>'));
redirect('/');
}
}
I'm just learning to use it as well, but don't you need three parameters? This is from their form validation page:
$this->form_validation->set_rules('email', 'Email', 'required');
From http://codeigniter.com/user_guide/libraries/form_validation.html#validationrules
The field name - the exact name you've given the form field.
A "human" name for this field, which will be inserted into the error message. For example, if your field is named "user" you might give it a human name of "Username". Note: If you would like the field name to be stored in a language file, please see Translating Field Names.
The validation rules for this form field.
I have a form on my website header where i allow the user to log in with his username/password... then i POST to /signin page and check if the username exists to allow the user to log in.. if there is a problem upon login i output these errors...
i tried using the following code to show a custom error but with no luck
if ($this->form_validation->run() == false){
$this->load->view("login/index", $data);
}else{
$return = $this->_submitLogin();
if ($return == true){
//success
}else{
$this->form_validation->set_message('new_error', 'error goes here');
//error
}
$this->load->view("login/index", $data);
}
how does set_message work and if this is the wrong method, which one allow me to show a custom error in this case?
EDIT :
validation rules:
private $validation_rules = array(
array(
'field' => 'username',
'label' => 'Username',
'rules' => 'trim|required|callback__check_valid_username|min_length[6]|max_length[20]|xss_clean'
),
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'trim|required|min_length[6]|max_length[32]'
),
);
The set_message method allows you to set your own error messages on the fly. But one thing you should notice is that the key name has to match the function name that it corresponds to.
If you need to modify your custom rule, which is _check_valid_username, you can do so by perform set_message within this function:
function _check_valid_username($str)
{
// Your validation code
// ...
// Put this in condition where you want to return FALSE
$this->form_validation->set_message('_check_valid_username', 'Error Message');
//
}
If you want to change the default error message for a specific rule, you can do so by invoking set_message with the first parameter as the rule name and the second parameter as your custom error. E.g., if you want to change the required error :
$this->form_validation->set_message('required', 'Oops this %s is required');
If by any chance you need to change the language instead of the error statement itself, create your own form_validation_lang.php and put it into the proper language folder inside your system language directory.
As you can see here, you can display the custom error in your view in the following way:
<?php echo form_error('new_error'); ?>
PS: If this isn't your problem, post your corresponding view code and any other error message that you're getting.
The problem is that your form is already validated in your IF part! You can fix the problem by this way:
if ($this->form_validation->run() == false){
$this->load->view("login/index", $data);
}else{
$return = $this->_submitLogin();
if ($return == true){
//success
}else{
$data['error'] = 'Your error message here';
//error
}
$this->load->view("login/index", $data);
}
In the view:
echo $error;
The CI way to check user credentials is to use callbacks:
$this->form_validation->set_rules('username', 'Username', 'callback_username_check');
...
public function username_check($str) {
// your code here
}
I recommend you to read CI documentation: http://codeigniter.com/user_guide/libraries/form_validation.html
The way I did this was to add another validation rule and run the validation again. That way, I could keep the validation error display in the view consistent.
The following code is an edited excerpt from my working code.
public function login() {
$this->form_validation->set_rules('email', 'Email', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
$data['content'] = 'login';
if($this->form_validation->run()) {
$sql = "select * from users where email = ? and password = ?";
$query = $this->db->query($sql, array($this->input->post('email'), $this->input->post('password')));
if($query->num_rows()==0) {
// user not found
$this->form_validation->set_rules('account', 'Account', 'callback__noaccount');
$this->form_validation->run();
$this->load->view('template', $data);
} else {
$this->session->set_userdata('userid', $query->id);
redirect('/home');
}
} else {
$this->load->view('template', $data);
}
}
public function _noaccount() {
$this->form_validation->set_message('_noaccount', 'Account must exist');
return FALSE;
}
Require Codeigniter 3.0
Using callback_ method;
class My_controller extends CI_Controller {
function __construct() {
parent::__construct();
$this->form_validation->set_message('date_control', '%s Date Special Error');
}
public function date_control($val, $field) { // for special validate
if (preg_match("/^[0-9]{2}.[0-9]{2}.[0-9]{4}$/", $val)) {
return true;
} else {
return false;
}
}
public function my_controller_test() {
if ($this->input->post()) {
$this->form_validation->set_rules('date_field', 'Date Field', 'trim|callback_date_control[date_field]|xss_clean');
if ($this->form_validation->run() == FALSE) {
$data['errors']=validation_errors();
$this->load->view('my_view',$data);
}
}
}
}
Result:
if date = '14.07.2017' no error
if date = '14-7-2017' Date Field Date Special Error