How to validate a form in Kohana 3.3.1 - validation

I'm trying to validate a form but it doesn't show validation errors and if field is empty, it saves. How to validate form?
My code is:
public function action_upload()
{
if($_POST) {
$name = array(
'name' => Arr::get($_POST, 'name')
);
$validate = Validation::factory($name)
->rule('name', 'not_empty');
try {
$save = Model_Offers::Save($this->user['user_id'], $name);
}
catch (ORM_Validation_Exception $e)
{
$result = $e->errors('models');
echo '<pre>';
print_r($result);
exit;
}
}
}
My view is:
<form id="myForm" action="<?php echo URL::base()?>user/upload" method="post" enctype="multipart/form-data">
<div class="input-group">
<label for="file">Name: </label>
<input type="text" name="name" id="name"><br>
</div>
</form>

You created the validation object, but you forgot to actually apply the rules you assigned. Simply do this by calling
$validate->check()
It'd be best to put this in an if-else statement
if($validate->check()){
//Save object
}
else{
//Get errors (use $validate->errors())
}
Hope that helps! :)

Related

Set "custom" withErrors without Request->validation in Laravel

I want to display an error in a form, but it cannot be checked via validation.
Blade
<form action="/githubuser" methode="GET">
<div class="error">{{ $errors->first('CustomeError') }}</div>
<input type="text" name="userName" placeholder="GitHub Username ..." value="John12341234">
#if($errors->has('userName'))
<div class="error">{{ $errors->first('userName') }}</div>
#endif
<input type="submit" value="SUBMIT">
</form>
The Problem is that I start an api call after validation. and if I don't get "GitHubUser" as a response, I want to print an error message in the blade. GitHub user not found.
Controller
public function show(Request $request)
{
$rules = ['userName' => 'required'];
$validator = \Validator::make($request->input(), $rules);
if ($validator->fails()) {
return redirect('/')
->withErrors($validator)
->withInput();
}
$data = $this->gitHubUserService->getUserData($request->input('userName'));
/* User on Github not Found **/
if (! $data) {
// >>> THE LINE BELOW IS MY PROBLEM! <<<
return view('form')->withErrors($validator);
}
// ....
}
At the end of the day I want the line <div class="error">{{ $errors->first('CustomeError') }}</div> to be displayed in the blade.
Is this possible? Thanks in advance!
The original validator is not getting any error, because there are none. So, just add a new error to the errors inside of your if body before returning form view:
if(! $data){
$validator->errors()->add('customError', 'Github User not found!');
return view('form')->withErrors($validator);
}

Error: page requested not found codeigniter

Controller
public function index()
{
//load session library
$this->load->library('session');
if($this->session->userdata('user')){
// redirect('home');
$this->load->view('heropage');
}
else{
$this->load->view('login_page');
}
}
public function login(){
$email = $_POST['email'];
$password = $_POST['password'];
$data = $this->Users_model->login($email, $password);
if($data)
{
$id=$data[0]->id;
$first_name=$data[0]->firstname;
$last_name=$data[0]->lastname;
$grade=$data[0]->grade;
$points=$data[0]->points;
$this->session->set_userdata('user_id',$id);
$this->session->set_userdata('lname',$last_name);
$this->session->set_userdata('user', $email);
$this->session->set_userdata('fname',$first_name);
$this->session->set_userdata('grade',$grade);
$this->session->set_userdata('pts',$points);
$this->getImg();
redirect('home');
}
else{
header('location:'.base_url().$this->index());
$this->session->set_flashdata('error','Invalid login. User not found'); }
}
View
<?php if(isset($_SESSION['success'])) :?>
<div class="alert alert-success"><?=$_SESSION['success'];?></div>
<?php endif; if(isset($_SESSION['error'])) :?>
<div class="alert alert-warning"><?=$_SESSION['error'];?></div>
<?php endif;?>
<!-- End alerts -->
<form action="<?php echo base_url();?>index.php/User/login" method="post" accept-charset="utf-8">
<div class="form-group">
<label>Email:</label>
<input type="text" class="form-control" name="email" placeholder="Email">
<?php echo form_error('email'); ?>
</div>
<div class="form-group">
<label>Password:</label>
<input type="password" class="form-control"name="password" placeholder="Password">
<?php echo form_error('password'); ?>
</div>
<div class="form-group">
<button class="btn btn-sm btn-success" type="submit" align="center" name="login" class="submit">Log in</button>
</div>
</div>
</form>
model
public function login($email,$password)
{
$query = $this->db->get_where('users', array('email'=>$email));
if($query->num_rows() == 1 )
{
return $query->result();
}
}
Upon trying to log in, I got the error page cant be found. I want it to go to the home page if the session is correct. here is the error message:
404 Page Not Found
The page you requested was not found.
How can I solve the error because I have also set as needed in the routes
I think your form action should be <?php echo base_url(); ?>user/login
Also in your model you're not checking for password anywhere.
You're also not returning anything if the email is not found or more than 1 results are found -
($query->num_rows() == 1)
Model
public function login($email,$password)
{
$query = $this->db->get_where('users', array('email' => $email, 'password' => $password))->result(); // you should use row() here to return only 1 row.
return $query; // you should check the uniqueness of email on registration, not here -- not allow duplicate email on registration
}
Controller
public function login(){
$email = $_POST['email']; // $this->input->post('email');
$password = $_POST['password'];
$data = $this->Users_model->login($email, $password);
if( !empty($data) ) // if no result found it'll be empty
{
// your code
}
else{
header('location:'.base_url().$this->index());
$this->session->set_flashdata('error','Invalid login. User not found');
}
}
See, if this helps you.

Codeigniter Radio button form validation?

I want to validate three radio button inputs using codeigniter form validation rule:
HTML Page
<form action="<?php echo base_url('register')" ?> method="POST">
<input type="radio" name="cars" value="BMW">
<input type="radio" name="cars" value="Ferrari">
<input type="radio" name="cars" value="Jaguar">
<input type="submit" name="submitter">
</form>
Controller
public function register()
{
$this->form_validation->set_rules('cars', 'Cars', 'required');
if($this->form_validation->run() == TRUE)
{
i know what to do here
}
else
{
i know what to do here
}
}
How to do form validation in codeigniter for radio button in my case ?
Load library for form validation and other helpers in application/config/autoload.php
$autoload['libraries'] = array('form_validation');
$autoload['helper'] = array('form', 'url');
In your controller
public function register()
{
$this->form_validation->set_rules('cars', 'Cars', 'required');
if($this->form_validation->run() == TRUE)
{
echo "success";
}
else
{
$this->load->view('welcome_message');
}
}
In your view file use below code for printing validation errors
<?php echo validation_errors(); ?>
To show form error use form_error() function and to show all error use <?php echo validation_errors(); ?>
HTML PAGE
<form action="<?php echo base_url('register'); ?>" method="POST">
<?php echo form_error('cars'); ?>
<input type="radio" name="cars" value="BMW">
<input type="radio" name="cars" value="Ferrari">
<input type="radio" name="cars" value="Jaguar">
<input type="submit" name="submitter">
</form>
Controller
public function register(){
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('cars', 'Cars', 'required');
if($this->form_validation->run() == TRUE)
{
echo "i know what to do here"; //die;
}
else
{
echo "i know what to do here"; //die;
}
$this->load->view('welcome_message'); // your html view page
}
I think you are looking for in_list validation as an addition to required that has been mentioned by the others.
$this->form_validation->set_rules('cars', 'Cars', 'required|in_list[BMW,Ferrari,Jaguar]');
Also, as a self-reminder, since it took me 1 year to know about this.

Weird behaviour of CI after a redirect()

I have a strange bug during the password recovery process.
When a user loses his pwd, the app send an email with a token inside the recovery link ( http://localhost/reset-password/f38fd00aa975b28c70f54d948d20de40 for exemple ) This token is an unique key inside the user table.
In the routes.php, i have :
$route['reset-password/(:any)'] = "/user/reset_password_form/$1";// new password form
$route['reset-password'] = "/register/reset_password"; //simple email form
then, reset_password_form generates a form with the token as hidden input :
public function reset_password_form($hash = NULL) { //create form to change password, with user validation hash inside
$user_id = $this->user_model->get_id_by_confirmation_code(strip_tags($hash));
if (isset($user_id)) {
$this->data['validation_code'] = $hash;
$this->data['title'] = $this->lang->line('user_title_password_edit', FALSE);
$this->template->load('default', 'register/reset_password_form', $this->data);
}
else{
$this->session->set_flashdata('error', $this->lang->line('user_error_reset_password', FALSE));
redirect('reset-password');
}
the view:
<?php $attributes = array('class' => '');
echo form_open('user/edit_password', $attributes) ?>
<input type="hidden" id="validate" name="validate" value="<?=$validation_code?>">
<div class="form-group">
<input type="password" id="password" name="password" placeholder="Password" class="form-control" value="<?php echo set_value('password'); ?>">
</div>
<div class="form-group">
<input type="password" id="password_confirm" name="password_confirm" placeholder="Password confirmation" class="form-control">
</div>
<button type="submit" name="submit" class="btn btn-success">Change password</button>
</form>
Finally, the user/edit_password function changes the user password with a new one.
public function edit_password() { //get new password and change it
$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[6]');
$this->form_validation->set_rules('password_confirm', 'Confirm Password', 'trim|required|matches[password]');
$this->form_validation->set_rules('validate', 'Validate', 'trim|alpha_numeric|required');
if ($this->form_validation->run() === false) {
//STRANGE BUG
$URL = '/reset-password/'.$this->input->post('validate');
$this->session->set_flashdata('error', validation_errors());
redirect($URL);
}
else {
//change pssword
}
}
The bug happen when the form validation fail : i'm suposed to be redirected to the previous form ( /reset-password/hash) with a flashdata error message, but the error message dont display.
Much more weird : even if i'm on the right form ( but without error message) if i decides to click on another menu item (for exemple /home) , it immediately displays the /reset-password form ( /register/reset_password in the routes) with the error message i was supposed to get previously.
As if the full php instruction was kept in stamp and launched after whatever action.
PS : as edit_password() and reset_password_form() are in the same controller, i could have used $this->reset_password_form($hash) instead of redirect() but it has exactly the same effect !
ps2: here is the register/reset_password:
public function reset_password() {
//display forgotten password form page
$this->data['title'] = 'Forgotten password';
$this->template->load('default', 'register/reset_password', $this->data);
}
you recovery link http://localhost/reset-password/f38fd00aa975b28c70f54d948d20de40 is not finding controller. CI is looking for your token number as controller

Using the Remember me feature with Sentry in Laravel 4

I'm trying to get a login form to 'remember' the user logging in and I just can't work out how to do it.
Here's my controller
public function getLogin()
{
// Return the view with the data
return View::make('users.login');
}
public function postLogin()
{
// Gather Sanitized Input
$input = array(
'email' => Binput::get('email'),
'password' => Binput::get('password'),
'rememberMe' => Binput::get('rememberMe')
);
// Set Validation Rules
$rules = array (
'email' => 'required|min:4|max:64|email',
'password' => 'required|min:6'
);
//Run input validation
$v = Validator::make($input, $rules);
if ($v->fails())
{
// Validation has failed
return Redirect::to('users/login')->withErrors($v)->withInput();
}
else
{
try
{
//Check for suspension or banned status
$user = Sentry::getUserProvider()->findByLogin($input['email']);
$throttle = Sentry::getThrottleProvider()->findByUserId($user->id);
$throttle->check();
// Set login credentials
$credentials = array(
'email' => $input['email'],
'password' => $input['password']
);
// Try to authenticate the user
$user = Sentry::authenticate($credentials, $input['rememberMe']);
Sentry::loginAndRemember($user);
}
catch (Cartalyst\Sentry\Users\UserNotFoundException $e)
{
// Sometimes a user is found, however hashed credentials do
// not match. Therefore a user technically doesn't exist
// by those credentials. Check the error message returned
// for more information.
Session::flash('error', 'Invalid username or password.' );
return Redirect::to('users/login')->withErrors($v)->withInput();
}
catch (Cartalyst\Sentry\Users\UserNotActivatedException $e)
{
echo 'User not activated.';
Session::flash('error', 'You have not yet activated this account.');
return Redirect::to('users/login')->withErrors($v)->withInput();
}
// The following is only required if throttle is enabled
catch (Cartalyst\Sentry\Throttling\UserSuspendedException $e)
{
$time = $throttle->getSuspensionTime();
Session::flash('error', "Your account has been suspended for $time minutes.");
return Redirect::to('users/login')->withErrors($v)->withInput();
}
catch (Cartalyst\Sentry\Throttling\UserBannedException $e)
{
Session::flash('error', 'You have been banned.');
return Redirect::to('users/login')->withErrors($v)->withInput();
}
return Redirect::to('/');
}
}
/**
* Logout
*/
public function getLogout()
{
Session::flush();
Sentry::logout();
return Redirect::to('/');
}
And here's my View
#extends('layouts/master')
{{-- Web site Title --}}
#section('title')
#stop
{{-- Content --}}
#section('content')
<div class="tck-well span6 offset3">
<h1>Login</h1>
<form class="" action="{{ URL::to('users/login') }}" method="post">
{{ Form::token(); }}
<div class="control-group {{ ($errors->has('email')) ? 'error' : '' }}" for="email">
<label class="control-label" for="email">E-mail</label>
<div class="controls">
<input name="email" id="email" value="{{ Request::old('email') }}" type="text" class="input-xlarge" placeholder="E-mail">
{{ ($errors->has('email') ? $errors->first('email') : '') }}
</div>
</div>
<div class="control-group {{ $errors->has('password') ? 'error' : '' }}" for="password">
<label class="control-label" for="password">Password</label>
<div class="controls">
<input name="password" value="" type="password" class="input-xlarge" placeholder="New Password">
{{ ($errors->has('password') ? $errors->first('password') : '') }}
</div>
</div>
<div class="control-group" for"rememberme">
<div class="controls">
<label class="checkbox inline">
<input type="checkbox" name="rememberMe" value="1"> Remember Me
</label>
</div>
</div>
<div class="form-actions">
<input class="button button-large button-secondary" type="submit" value="Log In">
Forgot Password?
</div>
</form>
</div>
#stop
Can someone help point me in the right direction please?
You could also use the helper method:
if( Input::get('rememberMe') ) {
$user = Sentry::authenticateAndRemember($credentials)
} else {
$user = Sentry::authenticate($credentials, false);
}
Similar to Devo's
// Try to log the user in
Sentry::authenticate(Input::only('email', 'password'), Input::get('remember-me', 0));
// For the view page
<input type="checkbox" name="remember-me" id="remember-me" value="1" /> Remember me;
Instead of,
$user = Sentry::authenticate($credentials, $input['rememberMe']);
Use,
if(!empty($input['rememberMe'])) {
$user = Sentry::authenticate($credentials, true);
} else {
$user = Sentry::authenticate($credentials, false);
}
And make sure you are getting some value in $input['rememberMe'].
From GitHub it seems setting gc_maxlifetime in php.ini (or .htaccess) is sometimes necessary as well..
session.gc_maxlifetime = 2592000
In app/config/session.php add this lines:
'lifetime' => 999999,
'expire_on_close' => false,

Resources