CodeIgniter jQuery validator library not work

2019-08-07 13:50发布

问题:

anyone can help me how to configure CodeIgniter jQuery validator library

Jquery_validation https://github.com/GuriK/CodeIgniter-jQuery-Validator

my Controller

public function create_action() 
    {
            $now = date('Y-m-d H:i:s');
            $data = array(
        'nama'       => $this->input->post('nama',TRUE),
        'email'      => $this->input->post('email',TRUE),
        );

            $this->Register_model->insert($data);
    }

my View

    <span>
<i><img src="<?php echo base_url();?>assets/frontend/images/name.png" alt="" /></i>
 <input type="text" class="textbox" name="nama" placeholder="Nama"></span>

回答1:

Strongly recommend that First of All "Always Read Documents Carefully"

The Author of CodeIgniter jQuery validator library has clearly mentioned all the necessary steps to get this working except one thing that you have to add jQuery validation plugin in your html head :D Well, for experience players that was unnecessary but for beginner for sure it must be mentioned there..

Step - 1: Download zip file from CodeIgniter jQuery validator & place library/Jquery_validation.php from there to your CodeIgniter/application/library/Jquery_validation.php


Step - 2: load this library in your Controller $this->load->library('jquery_validation'); or you can auto load this library by putting the code $autoload['libraries'] = array('jquery_validation'); in CodeIgniter/application/config/autoload.php.


Step - 3: Create some required code to get this work.

// set validation rule to jquery validation lib
$this->jquery_validation->set_rules($rules);
// set validation message to jquery validation lib
$this->jquery_validation->set_messages($messages);
// create jquery validation script for form #login-form
$validation_script = $this->jquery_validation->run('#login-form');

Step - 4: Don't forget to add jQuery validation plugin in your view

& finally here is full working example code:

<?php
// security first always....
(defined('BASEPATH') or exit('No direct script access allowed'));
/**
 * Class Controller
 *
 * Class Logins Controller to handle login & logout
 */
class Logins extends CI_controller
{
    /**
     * Class Constructor
     */
    public function __construct()
    {
        // execute parent class constructor
        parent::__construct();
        // load helpers
        $this->load->helper(array('form', 'url', 'security'));
        // load codeigniter for validation lib
        $this->load->library('form_validation');
        // load jquery validation lib
        $this->load->library('jquery_validation');
    }
    /**
     * Default method to execute if method name missing
     * @return [type] [description]
     */
    public function index()
    {
        // check if user login or not
        if (!$this->session->userdata('name')) {
            // form validation rules
            $rules = array(
                array(
                    'field' => 'name',
                    'label' => 'Name',
                    'rules' => 'trim|required|xss_cleaned|min_length[3]|max_length[25]',
                ),
                array(
                    'field' => 'pass',
                    'label' => 'Secret Password',
                    'rules' => 'required',
                ),
            );
            // form validation message
            $messages = array(
                'name' => array(
                    'required' => "jQuery validation User Name is required",
                    'min_length' => "jQuery validation, Please enter more then 3 char",
                    'max_length' => "jQuery validation, Please enter less then 25 char",
                ),
                'pass' => array('required' => "jQuery validation Password is required"),
            );
            // set validation rule to jquery validation lib
            $this->jquery_validation->set_rules($rules);
            // set validation message to jquery validation lib
            $this->jquery_validation->set_messages($messages);
            // create jquery validation script for form #login-form
            $validation_script = $this->jquery_validation->run('#login-form');
            // collect script and send to view
            $data = ['validation_script' => $validation_script];
            // show login view
            $this->load->view('form', $data);
        }
        // if already logged in, show other view
        else {
            // get name from session login flag
            $name = $this->session->userdata('name');
            // load view
            $this->load->view('form', $name);
        }
    }
    /**
     * login Form POST Method to verify Users identity
     * @return [type] [description]
     */
    public function do_login()
    {
        // if POST made then only
        if ($this->input->post()) {
            // form validation rule for codeigniter validation
            $rules = array(
                array(
                    'field' => 'name',
                    'label' => 'Name',
                    'rules' => 'trim|required|xss_cleaned|min_length[3]|max_length[25]',
                ),
                array(
                    'field' => 'pass',
                    'label' => 'Secret Password',
                    'rules' => 'required',
                ),
            );
            // custom validation message for server side form validation
            $this->form_validation->set_message('required', 'CodeIgniter validation, The %s is required filed');
            $this->form_validation->set_message('min_length', 'CodeIgniter validation, The %s Please enter more then 3 char');
            $this->form_validation->set_message('max_length', 'CodeIgniter validation, The %s Please enter less then 25 char');
            // form validation using codeigniter built-in lib
            $this->form_validation->set_rules($rules);
            // check validation
            if ($this->form_validation->run() === false) {
                // validation failed
                $this->load->view('form');
            } else {
                // safe from CSRF, use 2nd param as TRUE in POST
                $name = $this->input->post('name', true);
                $pass = $this->input->post('pass', true);
                // if result
                if ($name == 'admin' && $pass == 'admin') {
                    $sess_login = array(
                        'name' => $name,
                    );
                    // set session login flag
                    $this->session->set_userdata($sess_login);
                    // load view
                    $this->load->view('form', $name);
                } else {
                    redirect('logins');
                }
            }
        } else {
            redirect('logins');
        }
    }
    /**
     * Log Out Method
     * @return [type] [description]
     */
    public function userlogout()
    {
        $this->session->unset_userdata('name');
        redirect('logins');
    }
}
/* End of file logins.php */
/* Location: ./application/controllers/logins.php */

& here is view source code:

<?php
$name = $this->session->userdata('name');
?>
<!DOCTYPE html>
<html>
<head>
    <title>CodeIgniter jQuery validation</title>
    <!-- load bootstrap css -->
    <link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <!-- load jquery library -->
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <!-- load bootstrap js -->
    <script type="text/javascript" src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <!-- load jquery validation javascript plugin -->
    <script type="text/javascript" src="//cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
    <!-- echo jQuery form validation script from Controller -->
    <script type="text/javascript">
        <?php echo $validation_script;?>
    </script>
</head>
<body>
    <div class="jumbotron vertical-center">
        <?php if ($name !== false): ?>
            <div class="container">
                <div class="alert alert-success">Wohoo!! You made it.. <?php echo $name ?> <a href="<?php echo base_url()?>logins/userlogout" class="btn btn-danger">Log Out</a></div>
            </div>
        <?php else: ?>
            <div class="container">
                <?php echo (validation_errors()) ? '<div class="alert alert-danger">'.validation_errors().'</div>' : ''; ?>
                <?=form_open('logins/do_login', 'id="login-form" class="form-controller"'); ?>
                <fieldset>
                    <legend>Login Information</legend>
                    <div class="form-group">
                        <label for="name">Name</label>
                        <input type="text" class="form-control" name="name" id="name" placeholder="Please enter your user name here" value="<?php echo set_value('name'); ?>">
                    </div>
                    <div class="form-group">
                        <label for="password">Secret Password</label>
                        <input type="password" class="form-control" id="password" name="pass" placeholder="Please enter your password here" value="<?php echo set_value('pass'); ?>">
                    </div>
                </fieldset>
                <div class="form-group row">
                  <div class="offset-sm-2 col-sm-10">
                    <button type="submit" class="btn btn-primary">Sign in</button>
                </div>
            </div>
            <?=form_close();?>
        </form>
    </div>
<?php endif ?>
</div>
</body>
</html>

You can see the demo by using http://localhost/CodeIgniter/logins url in your browser.