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>
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 ?> Log Out</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.
Related
Another CI Validation Error here. I've tried searching and from what I can see, the code I have is OK. The validation runs - if I just echo out a "Validation Failed" string from the controller, it displays.
But I cannot seem to get it to display in an actual view. Even if I have a single line in the view (ie echo validation_errors(); ), there are no errors output even though it fails validation.
Any pointers would be greatly appreciated :)
Controller
public function add() {
if ($this->form_validation->run('user_add_edit') == FALSE)
{
//Validation failed
$this->load->view('templates/header_generic');
$this->load->view('templates/navigation');
$this->load->view('user/add_user_form');
$this->load->view('templates/footer_generic');
}
else
{
echo "Form validated!";
}
}
View (Partial)
<div class="panel-body">
<?php echo validation_errors(); ?>
<?php echo form_open('user/add'); ?>
<label for="email">
Email Address
</label><br />
<div class="form-group input-group <?php echo null === form_error('email') || is_null(form_error('email')) ? 'form-group has-error' : ''; ?>">
<span class="input-group-addon">#</span>
<?php echo form_input($email_attr, set_value('email')); ?>
</div>
<br />
<?php echo form_error('email');?>
<br />
<?php echo form_fieldset("Password"); ?>
jfkdjflkdjflks
<?php echo form_fieldset_close(); ?>
<br />
<?php echo form_submit("submit", "Add New User", "class='btn btn-success'"); ?>
</form>
</div>
Form Validation
$config = array(
'user_add_edit' => array(
array(
'field' => 'email',
'label' => 'Email Address',
'rules' => 'trim|required|valid_email|is_unique[user.email]',
'errors' => array(
'required' => 'You must enter a %s',
'valid_email' => '%s is not a valid email address',
'is_unique' => 'This email address already exists'
)
),
Having MY_Form_validation.php improperly set up can mess up with setting of form rules via config file.
Fix
In application/libraries/MY_Form_validation.php - replace your constructor with the below code or just follow the changes below by adding the $config parameter.
function __construct($config = array()){
parent::__construct($config);
$this->CI =& get_instance();
}
It's also a possibility that the value of $config variable is being overwritten that's happening inside application/config/form_validation.php. Check for it as well.
Alternative:
Load the form_validation.php config file from the controller method and pass the relevant config item to set_rules(..) like in the following.
public function add() {
$this->load->config('form_validation');
$this->form_validation->set_rules($this->config->item('user_add_edit'));
if ($this->form_validation->run() == FALSE)
{
//Validation failed
$this->load->view('templates/header_generic');
$this->load->view('templates/navigation');
$this->load->view('user/add_user_form');
$this->load->view('templates/footer_generic');
}
else
{
echo "Form validated!";
}
}
I have many inputs without connect any models in my form like this:
my view is this and I put this to show to other user to detect what is my problem
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* #var $this yii\web\View */
/* #var $model app\models\Tour */
$this->title = 'ثبت تور';
$this->registerJsFile('#web/storage/js/agency/tour.js', ['depends' => [
\yii\web\JqueryAsset::className(),
\yii\validators\ValidationAsset::className(),
\yii\widgets\ActiveFormAsset::className()],
]);
<?php $form = ActiveForm::begin([
'id' => 'jqTourStep1Form'
]); ?>
<div class="col-xs-6 pull-right padding0">
<?= $form->field($model, 'title_fa')->textInput() ?>
</div>
<div class="form-group col-xs-4 padding0 pull-right idTesttt">
<label class="control-label">Start Date</label>
<input type="text" name="startDate[]" id="startDateTest" class="form-control">
<span class="help-block"></span>
</div>
<?= Html::submitButton('Next', ['class' => 'btn btn-success']) ?>
<?php ActiveForm::end(); ?>
tour.js :
/* Validation */
$('#jqTourStep1Form').yiiActiveForm('add', {
id: 'startDateTest',
name: 'startDate',
container: '.idTesttt',
input: '#startDateTest',
error: '.help-block',
validate: function (attribute, value, messages, deferred, $form) {
yii.validation.required(value, messages, {message: "Validation Message Here"});
}
});
and I want to Client validate this inputs in Yii 2.
how can I do this ?
You should use each core validator: Each Validator. But you should use ActiveForm to generate form.
public function rules()
{
return [
// checks if every category ID is an integer
['categoryIDs', 'each', 'rule' => ['integer']],
]
}
Add JS code to client side validation:
jQuery('#form-id').yiiActiveForm("add", {
"id": "input-id",
"name": "input-name",
"container": "#container-id or unique .container-class of this input",
"input": "#input-id or unique .input-class",
"validate": function (attribute, value, messages, deferred, $form) {
yii.validation.required(value, messages, {"message": "Validation Message Here"});
}
}
);
You can create object of specific validator class without using models:
$validator = new \yii\validators\DateValidator();
and validate any value
$error = null;
$validator->validate($startDate, $error);
method validate() will return boolean and add to variable $error message about error.
You can read and choose specific validator on this page
I have a fairly standard CI3 site up and running. I have created my own base controller, called MY_Controller, and all my page controllers extend this.
MY_Controller.php
public function __construct() {
parent::__construct();
}
/**
* Display the view. This function wraps up all the teplates,
* sets the page title, adds all the requested Javascript and CSS,
* and passes along any data.
* #param string $view The name of the content view to display
* #param array $data (Optional) ÏAn array of any data to pass along
*/
protected function showView($view, $data = null) {
if ($data === null) {
$data = array();
}
// call all the template pieces
$this->load->view('header', $data);
$this->load->view('mainNav', $data);
$this->load->view($view, $data);
$this->load->view('footer', $data);
}
Each page controller calls $this->showView($viewName, $data); when it's ready to display results or whatever.
I have a form located on my login controller, Login.php.
Login.php has a method called "submit".
public function submit() {
$cfg = array(
array(
'field' => 'username',
'label' => 'Username',
'rules' => 'required|trim|alpha_numeric|xss_clean|min_length[3]|max_length[50]'
),
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'required|trim|alpha_numeric|xss_clean|min_length[3]|max_length[50]'
)
);
if ($this->form_validation->set_rules($cfg) === false) {
$this->showView("login");
} else {
$data = array(
'password' => $this->input->post('password')
);
if (filter_var($this->input->post('username'), FILTER_VALIDATE_EMAIL) === false) {
$data['username'] = $this->input->post('username');
} else {
$data['email'] = $this->input->post('username');
}
$user = $this->User->getUserFromLogin($data);
if ($user !== false) {
$sessionData = array(
'userName' => $user->userName,
'email' => $user->email,
'authToken' => $user->authToken,
'lastSeen' => date("Y-m-d")
);
// Add user data to session
$this->session->set_userdata('userLoggedIn', true);
$this->session->set_userdata('userData', $sessionData);
$this->showView("home");
} else {
$data = array(
'error_message' => 'User could not be loaded.',
);
$this->showView("login", $data);
}
}
}
My Login view, login.php
<div class="wrapper style1">
<article id="work">
<header>
<h2>Login!</h2>
<?=validation_errors();?>
</header>
<div class="container 50%">
<section>
<form method="post" action="login/submit">
<div>
<div class="row">
<div class="6u">
<input type="text" name="username" id="username" placeholder="username or email" value="<?=set_value('username');?>" />
</div>
<div class="6u">
<input type="password" name="password" id="password" placeholder="password" />
</div>
</div>
<div class="row">
<div class="12u">
<ul class="actions">
<li>
<input type="submit" value="Sign in!" />
</li>
</ul>
</div>
</div>
</div>
</form>
<footer>
<div>...or sign in with Facebook!</div>
<fb:login-button scope="public_profile,email" onlogin="checkLoginState();"></fb:login-button>
</footer>
</section>
</div>
</article>
</div>
Upon successful submission of the form, I'm expecting it to redirect me to home, which it is, however, the URI is localhost/login/submit instead of localhost/home.
Likewise with my logout controller, upon logout, it navigates to the URI localhost/logout/logout, which generates a 404.
I can't figure out why it doesn't redirect to the controller I've specified in the showView() method.
I'm not using any custom routing tricks.
The method showView simply loads in the values extra templates you want as well as the data you sent. I believe you are looking to do a redirect when you need to move off of pages instead of just rerendering the page the way you are.
redirect($uri = '', $method = 'auto', $code = NULL)
If this doesn't suffice your needs please include you routes and your logout controller to see what's going on in the other scenario you mentioned.
On successful authentication, instead of
$this->showView("home");
you should change that to redirect(),
redirect("controller/method/parameters if any");
there is method call showview(). To load view you have to use
$this->load->view("login");
as well as redirect should be
redirect('controller_name/method_name');
Here is the controller, when I click the login button, nothing happens. What I want is to load the success screen when user data is validated and show error messages when user data is not validated.
I have set my base_controller as Login
<?php
class Login extends CI_Controller {
/**
*
* load the magazines
*/
function __construct(){
parent::__construct();
$this->load->library('form_validation');
$this->load->model('User','National_Holiday','Updated_Holiday');
}
public function index() {
$this->load->view('login');
}
/**
*
* add a magazine
*/
public function login(){
$this->form_validation->set_rules(array (
array(
'field' => 'username',
'label' => 'username',
'rules' => 'required',
) ,
array(
'field' => 'password',
'label' => 'password',
'rules' => 'required|is_numeric',
),
));
$this -> form_validation ->set_error_delimiters('<div class="alert alert-error">','</div>');
if(!$this->form_validation->run()){
$this->load->view('login');
}
else {
$this->load->view('national_holiday_screen');
}
}
}
here is the view
<?php echo validation_errors(); ?>
<form method="post">
<!-- LOGIN DIV STARTS HERE -->
<div>
<div> <h2> Log In </h2></div>
<div>
<lablel for="username"> Username </label>
<input type="text" name="username" value=""/>
</div>
<div>
<label for="password"> Password </label>
<input type="password" name="password" value=""/>
</div>
<div>
<br>
<input type="submit" value="Login">
</div>
</div>
<!-- LOGIN DIV ENDS HERE -->
</form>
When I click the login button, nothing happens. What am I doing wrong?
You have to give action attribute in form tag, like this:
action="http://yoursitename.com/controllername"
in your case controllername is login.
For more help, you can refer:
[https://ellislab.com/codeigniter/user-guide/helpers/form_helper.html][1]
Hope this help!
this link shows how form_open() works, one of codeigniter's utility functions from the form helper libary.
In your case you would want this line of code:
<?php echo form_open('/login'); ?>
or something that you want to be the login url.
This line would replace
<form method="post">
in your html and when rendered would be something like
<form method="post" accept-charset="utf-8" action="http:/example.com/index.php/login" />
If you aren't familiar with URI routing, then you should read about that here](https://ellislab.com/codeigniter/user-guide/general/routing.html). I would recommedn setting up a route for you login, but the default format for a url is
example.com/class/function/id/
so yours might look like
example.com/login/login
And form_open() would then look like (even though its kind of cluncky)
<?php echo form_open('/login/login'); ?>
You can try below code
login.php controller file
<?php
class Login extends CI_Controller {
/**
*
* load the magazines
*/
function __construct(){
parent::__construct();
$this->load->library('form_validation');
$this->load->helper('url');
$this->load->model('User','National_Holiday','Updated_Holiday');
}
public function index() {
$this->load->view('login');
}
/**
*
* add a magazine
*/
public function validate(){
$this->form_validation->set_rules(array (
array(
'field' => 'username',
'label' => 'username',
'rules' => 'required',
) ,
array(
'field' => 'password',
'label' => 'password',
'rules' => 'required|is_numeric',
),
));
$this -> form_validation ->set_error_delimiters('<div class="alert alert-error">','</div>');
if(!$this->form_validation->run()){
$this->load->view('login');
}
else {
$this->load->view('national_holiday_screen');
}
}
}
Here I have loaded one helper to give action url in view file
$this->load->helper('url');
Also I have changed function name from login to validate as function name should not be similar to class name as constructor is already defined there
login.php view file
<?php echo validation_errors(); ?>
<form method="post" action = "<?php echo site_url("login/validate"); ?>">
<!-- LOGIN DIV STARTS HERE -->
<div>
<div> <h2> Log In </h2></div>
<div>
<lablel for="username"> Username </label>
<input type="text" name="username" value=""/>
</div>
<div>
<label for="password"> Password </label>
<input type="password" name="password" value=""/>
</div>
<div>
<br>
<input type="submit" value="Login">
</div>
</div>
<!-- LOGIN DIV ENDS HERE -->
</form>
Hope this will help you
I am working with Codeigniter and on top of it I have Bonefire (could this be the problem?), problem is everytime I want to validate the form with the use of Codeigniters helpers first condition of my conditional runns (FALSE) and on top of that function validation_errors() isn't ran... It is like my libraries for this helper aren't even loaded, despite doing everything by the book:
if ($this->form_validation->run() == FALSE)
{
echo $msg = validation_errors();
}
else
{
$this->load->user_model->insert($data);
echo $msg = "Registration successfull";
}
Let me post my form first (I ommited inline styles and classes by purpose):
<div class="" style="">
<h1 id="header" class="">Login/Register</h1>
<form action="/public/index.php/users/sportappregister" >
<div style=""><input id="email" type="text" name="email" value="email" style=""></div>
<div style=""><input id="pass" type="text" name="password" value="password" style=""></div>
<div style="" class=""><img class="" style="" src="<?php echo img_path(); ?>ikone/fb_login_icon.png" />Login with Facebook</div>
<div id="send" style="" class=""><input type="submit"> Submit </div>
<div id="cancel" style="" class=""> Cancel </div>
</form>
</div>
And as you can read from form action my controller is located in file "users" under public class "sportappregister", class Users extends Front_Controller as usuall and in this class at the end I make my own function to handle form like so:
public function sportappregister(){
$email= ($this->input->get("email"));
$pass = ($this->input->get("password"));
$data = array(
"email" => $email,
"password" => $pass );
// here I load my helper
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
// rules for my form
$this->form_validation->set_rules('email', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
if ($this->form_validation->run() == FALSE)
{
echo $msg = validation_errors();
}
else
{
$this->load->user_model->insert($data);
echo $msg = "Registration successfull";
}
}
You are using `GET` method. codeigniter form validation works with `POST` method only.
use CI form tags such as form_open() form_close() etc. to build form.
you can check This link
using get for login form will make your app insecure.
rest of your code seems ok to me.
just change this
$email= ($this->input->post("email")); //changed get to post in both
$pass = ($this->input->post("password"));
There's a few things I would change. Read the comments in the amended function below;
public function sportappregister()
{
// Load these first
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
// Now set the rules
$this->form_validation->set_rules('email', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
if ( $this->form_validation->run() == false )
{
echo validation_errors();
}
else
{
// Build the array after the form validation
$data = array(
'email' => $this->input->post('email'), // POST, not GET
'password' => $this->input->post('password')
);
// Load your model
$this->load->model('users_model');
if ( $this->users_model->insert($data) )
{
echo 'Registration successful';
}
else
{
echo 'Registration failed';
}
}
}
You have also loaded the form helper, but you're not using it. It makes building forms much, much easier.
http://ellislab.com/codeigniter/user-guide/helpers/form_helper.html
<?php echo form_open('users/sportappregister'); ?>