CodeIgniter Validation Not Displaying On Form - php

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!";
}
}

Related

CodeIgniter jQuery validator library not work

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.

Validation_errors() not showing in the view (CodeIgniter)

I'm working with my first application with CI and I'm having problems with the library form_validation.
The validation and my method are working fine, except for the fact that I can't get to show my error messages. I tried to show them individually, as the manual said, but didn't work. Tried to show them using echo validation_errors();, but the error messages are blank in my page.
So I make a test to put the code in the controller and they work! But they are shown in the beginning of the page. I used some javascript to make it visually better (moved it to where I want it to be shown), but it's not beautiful. I tried everything on the CodeIgniter and still did not get a good result. Please, someone could help me on this?
This is my controller User.php:
public function registrar() {
$this->load->library('form_validation');
$this->load->view('registrar');
$this->form_validation->set_rules('name', 'Nome', 'trim|required|min_length[7]',
array( 'required' => '<br>- Por favor, insira seu nome.',
'min_length' => '<br>- Por favor, insira seu nome completo.'));
// ..... other rules
if ($this->form_validation->run() == TRUE)
{
$password = $this->input->post('password');
$password_hash = password_hash($password, PASSWORD_BCRYPT);
$data = array(
'name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'password' => $password_hash
);
if ($this->user_model->insertUser($data))
{
$this->session->set_flashdata('error_msg','<p>Ok</p>');
redirect('user/registrar');
}
else
{
$this->session->set_flashdata('error_msg','<p>Not ok</p>');
redirect('user/registrar');
}
}
else
{
echo validation_errors('<div class="error">', '</div>'); //THIS LINE WORKS!!!
}
}
This is my view registrar.php:
<form action="" method="post" class="pure-form"> // using this only for css styling
<?php echo validation_errors(); ?> // THIS LINE DOESN'T WORKS :(
<?php echo form_open('user/registrar');?>
<fieldset>
<h1>Registrar</h1>
<div class="pure-control-group group gr-2">
<label for="email">Nome:</label>
<input type="text" class="pure-input-1" id="name" name="name" placeholder="Nome" value="<?php echo set_value('name');?>">
</div>
// ....... everything else
<input type="submit" class="pure-button pure-button-primary verde" value="Cadastrar" name="register_submit">
</div>
<?php echo form_close();?>
</form>
You are loading view page before the validation. That's the reason validation_errors are not showing in registrar.php.
$this->load->view('registrar');
Add this after else condition of validation or end of the function.

Insert into DB with codeigniter 3

im trying to add new post into my db. I have Model, Controller and View created. Actualy im using rest api for this, but now I want to do it with pure php powerd.
But After form validation is nothing. So when I try to post, nothuing happens.
Here is my code.
Model:
// Create
function create($data) {
// Insert data into DB
$this->db->insert('blog', $data);
return $this->db->insert_id();
}
Controller:
public function add() {
if ($this->ion_auth->is_admin()) {
// Validation rules
$this->form_validation->set_rules('title', 'Titel', 'required');
$this->form_validation->set_rules('teaser', 'Teaser', 'required');
$this->form_validation->set_rules('full', 'Volltext', 'required');
if (($this->form_validation->run() == FALSE)) {
$this->load->view('templates/backend/header', $this->data);
$this->load->view('pages/backend/blog/add', $this->data);
$this->load->view('templates/backend/footer');
} else {
if($this->input->post()) {
$data = array(
'title' => $this->input->post('title'),
'teaser' => $this->input->post('teaser'),
'full' => $this->input->post('full')
);
$this->blog_model->create($data);
redirect(base_url().'blog/');
}
}
} else {
redirect('login');
}
}
And at least my view:
<div class="uk-margin-top">
<?php $attributes = array("class" => "uk-panel uk-panel-box uk-form uk-margin-lage-bottom", "id" => "add-form", "method" => "post");
echo form_open("/backend/blog/add", $attributes); ?>
<div class="uk-form-row">
<label class="uk-form-label" for="title">Title</label>
<input id="title" class="uk-width-1-1 uk-form-large title redactor-box" name="title" placeholder="Beitragstitel" type="text"
value="<?php echo set_value('title'); ?>"/>
<span class="uk-text-danger"><?php echo form_error('title'); ?></span>
</div>
<div class="uk-form-row">
<label class="uk-form-label" for="teaser">Teaser</label>
<textarea id="teaser" class="uk-width-1-1 uk-form-large teaser redactor-box" name="teaser" data-uk-htmleditor></textarea>
<span class="uk-text-danger"><?php echo form_error('teaser'); ?></span>
</div>
<div class="uk-form-row">
<label class="uk-form-label" for="body">Body</label>
<textarea id="full" name="full" rows="4" placeholder="Ihre Nachricht"
value="<?php echo set_value('full'); ?>"></textarea>
<span class="uk-text-danger"><?php echo form_error('full'); ?></span>
</div>
<div class="uk-form-row">
<a class="uk-button uk-button-success" data-action="add-post">Submit</a>
</div>
<?php echo form_close(); ?>
</div>
So my problem is, when I click on my submit button - nothing. Maybe you can show me where my problem is.
Thank you!
For your controller, I think you are missing the form helper and validation library. I have included other comments in the code, but try this:
public function add() {
// you need to load these in:
$this->load->helper('form');
$this->load->library('form_validation');
// I am assuming ion_auth is working, however, I would try this code without
// this conditional statement
if ($this->ion_auth->is_admin()) {
// Validation rules
// Make sure the second parameter is right. I think Titel should be Title.
$this->form_validation->set_rules('title', 'Titel', 'required');
$this->form_validation->set_rules('teaser', 'Teaser', 'required');
$this->form_validation->set_rules('full', 'Volltext', 'required');
// added a triple === instead of == for stricter type checking
if (($this->form_validation->run() === FALSE)) {
// I am assuming $this->data is a property of your controller class
$this->load->view('templates/backend/header', $this->data);
$this->load->view('pages/backend/blog/add', $this->data);
$this->load->view('templates/backend/footer');
} else {
// Check if the form was submitted via $_POST method
if($this->input->post()) {
// I removed your $data array and created it in the model.
// I added a condition here to check if the data was successfully inserted
if ($this->blog_model->create()) {
redirect(base_url().'blog/');
} else {
// output an error message or redirect
}
}
}
} else {
redirect('login');
}
}
For your model, I think you were not passing any data to your model. Try the following for your model:
public function create()
{
// you need to pass an array of data or an object
// the array key corresponds to your db table column
// the array value corresponds to your views input field names
$data = array(
'name' => $this->input->post('title'),
'teaser' => $this->input->post('teaser'),
'full' => $this->input->post('full')
);
// returns true or false
return $this->db->insert('blog', $data);
}

CodeIgniter form validation helper always false

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'); ?>

How to validate associated models in cakephp

Hello Could please tell me.
How to validate associated models in cakephp?
i am using multiple model in one controller and controller name is 'AdminsController'.
These are Model in AdminsController
$uses=array('index','Static_page_view','Admin','Categories','Products', 'contact','User','Rams');'
now i want to validate 'Categories'(Model). i have defined set of validation rules. But not ale to validate. While when i use 'Admin'(MODEL) it works perfectly.
<?php
class AdminsController extends AppController {
public $uses=array('index','Static_page_view','Admin','Categories','Products', 'contact','User','Rams');
public function index()
{
if(!empty($this->request->data)) //this checks if the form is being submitted and is not empty
{
if($this->Admin->save($this->request->data))//this saves the data from the form and also return true or false
{
$this->Session->setFlash('The post was successfully added!');
$this->redirect(array('action'=>'index'));
}
else
{
$this->Session->setFlash('The post was not saved, please try again');
}
}
public function Add_Category()
{
if(!empty($this->request->data)) //this checks if the form is being submitted and is not empty
{
if($this->Rams->save($this->request->data))//this saves the data from the form and also return true or false
{
$this->Session->setFlash('The post was successfully added!');
$this->redirect(array('action'=>'Add_Category'));
}
else
{
$this->Session->setFlash('The post was not saved, please try again');
}
}
}
}
\app\Model\Admin
<?php
class Admin extends AppModel {
public $validate = array( ['Admin'] => array(
'name'=>array(
'title_must_not_be_blank'=>array(
'rule'=>'notEmpty',
'message'=>'Please Enter your Name!'
)
),
'email'=>array(
'body_must_not_be_blank'=>array(
'rule'=>'notEmpty',
'message'=>'Please Enter your Email!'
)
),
'phone'=>array(
'body_must_not_be_blank'=>array(
'rule'=>'notEmpty',
'message'=>'Please Enter your phone!'
)
),
'query'=>array(
'body_must_not_be_blank'=>array(
'rule'=>'notEmpty',
'message'=>'Please Enter your Query!'
)
)
));
}
\app\Model\categories
<?php
class Categories extends AppModel {
public $validate = array(
'name'=>array(
'title_must_not_be_blank'=>array(
'rule'=>'notEmpty',
'message'=>'Please Enter your Name!'
)
),
'email'=>array(
'body_must_not_be_blank'=>array(
'rule'=>'notEmpty',
'message'=>'Please Enter your Email!'
)
),
'phone'=>array(
'body_must_not_be_blank'=>array(
'rule'=>'notEmpty',
'message'=>'Please Enter your phone!'
)
),
'query'=>array(
'body_must_not_be_blank'=>array(
'rule'=>'notEmpty',
'message'=>'Please Enter your Query!'
)
)
);
}
\app\View\admins\index.ctp
<h2>Add a Post</h2>
<?php
echo json_encode($this->validationErrors);
//<!--create the form 2parameter:the post model and the 2nd is the form is submitted to which action-->
echo $this->Form->create('Admin', array('action'=>'index'));
echo $this->Form->input('name');//<!--We have not specified the field so type becomes text as the according to the database field type-->
echo $this->Form->input('email');
echo $this->Form->input('phone');
echo $this->Form->input('query');//<!--We have not specified the field so type becomes textarea as the according to the database field type-->
echo $this->Form->end('Create a Post');//<!--ends the form and create the text on button the same as specified-->
?>
\app\View\admins\category.ctp
<head>
<title>Admin Panel</title>
</head>
<body>
<div id="container">
<?php echo $this->element("header"); ?>
<div id="content">
<?php echo $this->element("left-content"); ?>
<div id="right-content">
<div id="upper">
<h3>Add SubCategory</h3>
</div><!---upper end--->
<?php
echo $this->Form->create('Admin', array('class' => "righform"));
$options = array();
?>
<fieldset class="textbox">
<label class="cate"><span>Main Category :</span>
<select name="parentId">
<?php foreach($name as $row){?>
<option value="<?php echo $row['Categories']['id'];?>"><?php echo $row['Categories']['name']; ?></option>
<?php } ?>
</select>
</label>
<br /><br /><br />
<label class="cate">
<?php echo $this->Form->input('name'); ?>
<br /><br /><br />
<label class="cate1">
<?php echo $this->Form->input('Description'); ?>
<br /><br /><br />
<br /><br /><br />
<td><button class="button" type="submit">Submit</button></td>
</fieldset>
</form>
</div>
</div><!---main content end--->
</div><!----content end---->
<?php echo $this->element("footer"); ?>
</div><!---container end---->
</body>
</html>
Thanks in Advance.
if your model are connected by relationship let say Admin has a OnetoOne/manytomany/onetomany relationship to Category
you can validate it by
$this->Admin->Category->saveAll(array('validate'=> 'only')); // pass 'only' string not only
or if you want to use any model which has no relation to default model then simply first load it on your current controller and then validate it let say category has no relation to current model then simply
$this->loadModel('category');
$this->category->set($this->data);
$this->category->saveAll(array('validate'=> 'only'));
Hope it will help you
you can use Multivalidatable behavior.
http://bakery.cakephp.org/articles/dardosordi/2008/07/29/multivalidatablebehavior-using-many-validation-rulesets-per-model

Categories