Codeigniter form validation rules order - php

I've set this rules on the controler
public function checkLogin()
{
$this->load->helper('form');
$this->load->library('form_validation');
$this->form_validation->set_rules(
'username',
'nombre de usuario',
'required',
array('required' => 'Debes introducir un %s.')
);
$this->form_validation->set_rules(
'pass',
'contraseña',
'required',
array('required' => 'Debes introducir una %s.')
);
$this->form_validation->set_rules(
'bad_login',
'login',
'callback_checkCredentials'
);
if ($this->form_validation->run() == FALSE) {
$this->load->view('header');
$this->load->view('login/login_view');
$this->load->view('footer');
} else {
$this->session->set_userdata('logged',true);
$this->session->set_userdata('user',$this->input->post('username'));
redirect('main');
}
}
public function checkCredentials(){
if($this->input->post('username') == $this->user && $this->input->post('pass') == $this->pass){
return true;
}else{
$this->form_validation->set_message('checkCredentials', 'El usuario/contraseña introducido no es correcto');
return false;
}
}
and the view
<div class="container">
<div class="col-md-4">
<?php $this->load->helper('form'); ?>
<?php echo form_open('checkLogin'); ?>
<?php echo form_error('bad_login'); ?>
<?php echo form_error('username'); ?>
<div class="form-group">
<?php echo form_label('Usuario:'); ?>
<?php echo form_input(array('id' => 'username', 'name' => 'username', 'class'=>'form-control', 'placeholder'=>"Nombre de usuario")); ?>
</div>
<?php echo form_error('pass'); ?>
<div class="form-group">
<?php echo form_label('Contraseña:'); ?>
<?php echo form_password(array('id' => 'pass', 'name' => 'pass', 'class'=>'form-control', 'placeholder'=>"Contraseña")); ?>
</div>
<?php echo form_submit(array('id' => 'submit', 'value' => 'Enviar', 'class'=>'btn btn-primary')); ?>
<?php echo form_close(); ?>
</div>
</div>
It's a login form with and input to the user and another to the password , but if the pass or the username are empty there is no need to check if pass and the username are correct(and show the message error), I'm not sure how to do that

You can simply do this:
$username = trim($this->input->post('usename'));
$password = trim($this->input->post('password'));
if(!empty($username) && !empty($password))
{
// do you validation
}
else
{
// maybe show error message
}

Related

How to call javascript function in callback function of codeigniter controller?

I want call the javascript function into callback function of codeigniter controller.
Controller: Callback function
public function email_exist($id) {
$this->db->where('email', $id);
$query = $this->db->get('login');
if (!$query->num_rows() > 0) {
$this->form_validation->set_message(__FUNCTION__, $this->email_validate());
return FALSE;
} else {
return TRUE;
}
Javascript: Alert function
function email_validate(){
alert('Invalid Email Id');
}
An uncaught Exception was encountered
Type: Error
Message: Call to undefined method Login::email_validate()
Filename: C:\wamp64\www\CodeIgniterProject1\application\controllers\login.php
Line Number: 46
login_form.php
<?php echo validation_errors(); ?>
<?php echo form_open_multipart(); ?>
<form name="form">
<div class="loginform">
<?php echo form_label('LOGIN', 'login'); ?>
</div>
<div class="email">
<?php echo form_input('email', 'E-MAIL', set_value('email')); ?>
</div>
<div class="password">
<?php echo form_password('password', 'PASSWORD', set_value('password')); ?>
</div>
<div class='checkbox'>
<?php
echo form_checkbox(array(
'name' => 'remember',
'id' => 'remember',
'value' => 'REMEMBER ME',
'checked' => FALSE,
'style' => 'margin:1px'
)) . form_label('REMEMBER ME', 'remember');
?>
</div>
<div class='btnlogin'>
<?php echo form_submit('login', 'LOGIN'); ?>
</div>
</form>
you cant do that in Codeigniter, use Codeigniter default form validation library
View here
if you want to add css for validation errors then try set_error_delimeters()
if you have bootstrap then use
alert alert-danger
class, else create one class
$this->form_validation->set_error_delimiters('<div class="alert alert-danger">', '</div>');
see
[other suggestions]
instead of putting all error in the top, you can also try
<?php
echo form_error('email');
form_input('email', 'E-MAIL', set_value('email'));
?>
other options is jquery validation or js validation, write js in view or external .js file
<?php
data = array(
'name' => 'username',
'id' => 'username', //use the id for jquery validation $('#username').on('blur', function() { });
'value' => 'johndoe',
'maxlength' => '100',
'size' => '50',
'style' => 'width:50%'
'onBlur' => 'email_validate();' //use this for javascript validation
);
echo form_input($data);
?>
im unable to comment, thats why posting as answer

form_validation returning false : codeigniter

Can anyone help me why my if code ($ this-> form_validation-> run () == FALSE) always returning FALSE even all fields are valid.
I have already loaded form_validation, url etc. the application is already working on a web server but when I deploy the application in localhost I hang on this error (from_validation always return false).
Here is my form:
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
$email = array(
'name' => 'email',
'id' => 'email',
'class'=> 'input',
'value' => set_value('email'),
'maxlength'=> 80,
'size' => 27,
);
$password = array(
'name' => 'password',
'id' => 'password',
'class' => 'input',
'value' => set_value('password'),
'size' => 27,
);
?>
<div class="row-fluid">
<div class="span8">
<b>Bienvenu!</b>
<p>Identifier-vous pour Accèder à Votre Compte</p>
<p>et Profiter de Nos Services en Ligne </p>
<?php $connect='users/login'; ?>
</div>
</div>
<div class="error"><strong><?=$this->session->flashdata('flashSuccess')?></strong></div>
<div class="login">
<?php $attributes = array('name' => 'loginf', 'autocomplete' => 'off' ); ?>
<?php echo form_open($connect,$attributes );?>
<div class="row-fluid">
<div class="span3">
<?php echo form_label('Adresse Email', $email['id']); ?>
</div>
<div class="span5">
<?php echo form_input($email); ?>
</div>
</div>
<div class="row-fluid">
<div class="span3">
<?php echo form_label('Mot de passe', $password['id']); ?>
</div>
<div class="span5">
<?php echo form_password($password); ?>
</div>
</div>
<div class="row-fluid">
<div class="span4">
<input class="btn" name="submit" type="submit" id="submit" value="Connexion" />
</div>
</div>
</div>
<?php echo form_close()?>
And my controller where the form_validation always returns false:
<?php
function login(){
$this->load->model('User_m');
$auto=FALSE;
$email=strtolower($this->input->post('email'));
$found="#bmc.com";
$res=strpos($email,$found) ;
if($res > 0){
$role=$this->User_model->getRole(strtolower($this->input->post('email')));
$tiers=$this->User_model->getTiers(strtolower($this->input->post('email')));
if($role=="VEND" && $tiers==""){
$auto=TRUE;
$this->form_validation->set_rules('email', 'Email Address', 'xss_clean|trim|required|valid_email');
}else{
$this->form_validation->set_rules('email', 'Email Address', 'xss_clean|trim|required|valid_email|callback_conten');
}
}else{
$this->form_validation->set_rules('email', 'Email Address', 'xss_clean|trim|required|valid_email|callback_conten');
}
$this->form_validation->set_rules('password', 'Password', 'xss_clean|trim|required|min_length[6]|max_length[20]|callback_password_check');
$this->_email = $this->input->post('email');
$s_pass=$this->security->xss_clean($this->input->post('password'));
$this->_password = sha1($this->_salt .$s_pass);
if($this->form_validation->run() == FALSE){
$this->tmpl_login['success']=NULL;
$this->tmpl_login['auth']='style="display:block"';
$this->tmpl_login['p_o']='style="display:none"';
$this->layout->view_menu_top('menul');
$this->layout->view('compte/login',$this->tmpl_login);
}else{
$this->auth->login('email');
$dv=$this->find_date_visit();
if($auto==FALSE){$this->_SendDynamiqueMessage($this->_email);}
$this->session->set_userdata('name',$this->find_name_user($this->_email));
$this->session->set_userdata('quality',$this->find_quality_user($this->_email));
$this->session->set_userdata('date_visite',$dv);
$this->session->set_userdata('email',$this->_email);
$user_agent = get_browser(null, true);
$this->db->query("insert into us_connexion values ('". $this->_email."',sysdate,'". $user_agent['platform']."','". $user_agent['parent']."')");
if(!$dv){
$this->session->set_userdata('date_visite','premier visite');
redirect('users/password');
}
redirect('users/index');
}
}
?>
PS: I used the codeigniter 2.0.2 version.
Any help please!
Thinks.

Cannot post radio value in Codeigniter

view:
<?php
$attr_form = array('class' => 'form-horizontal');
echo form_open('login/create', $attr_form); ?>
<div class="form-group">
<label class="col-sm-4 control-label">Gender</label>
<div class="col-sm-4">
<?php echo form_radio('gender', 'M'); ?>
<?php echo form_radio('gender', 'F'); ?>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-4 col-sm-8">
<?php
$data_submit = array('class'=> 'btn btn-info', 'name' => 'submit', 'value'=> 'Create Account');
echo form_submit($data_submit);?>
</div>
</div>
controllers:
function create ()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('gender', 'Gender', 'required');
if($this->form_validation->run() == FALSE)
{
$this->signup();
}
else
{
$this->load->model('parents_model');
if($query = $this->parents_model->create_member())
{
$data['main_content'] = 'successful';
$this->load->view('include/template', $data);
}
else
{
$this->signup();
}
}
}
model:
function create_member ()
{
$new_parents = array(
'gender' => $this->input->post('gender')
);
$insert = $this->db->insert('parents', $new_parents);
return $insert;
}
I just simplified the other form inputs.
Can anyone figure out whats wrong with my code? It cannot go to successful page.
Or do I use wrong form_radio code ?
I have tried many times! Please help me....
You have a syntax error.
$this->input->post->('gender')
should be:
$this->input->post('gender')
try this
$gender = $this->input->post('gender')['M'] ? 'M':'F';
$new_parents = array('gender' => $gender);
After I restarted my localhost, everything works again.
Cause I have created a column in the table without restarting!

Codeigniter form_validation not working

I have used codeigniter in the past but I am building a social network and I am working on the registration. I have autoloaded the form and form validation helpers. I have a form going to my user controller/register function and I have validation rules setup but its ignoring them and proceeding to the next page. I cant for the life of me figure out why. Any help is appreciated..the code and rules are not complete (obviously) but the validation should work at this point
VIEW
<?php echo validation_errors('<p class="error">'); ?>
<?php echo form_open('user/register/1'); ?>
<?php echo form_hidden('register_id', $randomcode); ?>
<?php echo form_label('First Name', 'first_name'); ?>
<?php echo form_input('first_name',set_value('first_name')); ?>
<br />
<?php echo form_label('Last Name', 'last_name'); ?>
<?php echo form_input('last_name',set_value('last_name')); ?>
<br />
<?php echo form_label('Gender', 'gender:'); ?>
<?php echo form_radio('gender', 'male'); ?> Male
<?php echo form_radio('gender', 'female'); ?> Female
<br />
<?php echo form_label('Date of Birth:', 'birthdate'); ?>
<?php echo form_date('birthdate'); ?>
<br />
<?php echo form_label('Zipcode:', 'zipcode'); ?>
<?php echo form_input('zipcode',set_value('zipcode')); ?>
<br />
<?php echo form_label('Email:', 'email'); ?>
<?php echo form_email('email',set_value('email')); ?>
<br />
<?php echo form_label('Password', 'password'); ?>
<?php echo form_password('password'); ?>
<br />
<?php echo form_label('Confirm', 'password2'); ?>
<?php echo form_password('password2'); ?>
<br />
<?php
$data = array(
'name' => 'submit',
'class' => 'big-blue-btn',
'value' => 'Sign Up'
);
?>
<?php echo form_submit($data); ?>
<?php echo form_close(); ?>
CONTROLLER
public function register($step){
if($step == 1){
$this->form_validation->set_rules('first_name', 'first_name', 'required');
$this->form_validation->set_rules('last_name', 'last_name', 'required');
if($this->form_validation->run() == FALSE){
//Views
$data['main_content'] = 'public/user/register1';
$this->load->view('public/template', $data);
} else {
//Post values to array
$data = array(
'register_id' => $this->input->post('register_id'),
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
'gender' => $this->input->post('gender'),
'birthdate' => $this->input->post('birthdate'),
'zipcode' => $this->input->post('zipcode'),
'email' => $this->input->post('email'),
'password' => $this->input->post('password'),
'password2' => $this->input->post('password2')
);
//Send input to model
$this->User_model->register1($data);
$data['show_sidebar'] = FALSE;
}
} elseif($step == 2){
//Send input to model
$this->User_model->register2($data);
} elseif($step == 3){
//Send input to model
$this->User_model->register3($data);
}
}
Review your code, you're missing a closing bracket on your first if.

Yii can't do the task, with getting no errors at all

I am using Yii framework and I want to make a registration page. I have created everything that was needed and when I register user I am getting no error at all but I can't find a record in database. so can you help me? here is my code:
SiteController.php :
public function actionRegister()
{
$model=new RegisterForm;
// uncomment the following code to enable ajax-based validation
if(isset($_POST['ajax']) && $_POST['ajax']==='register-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
if(isset($_POST['RegisterForm']))
{
$model->attributes=$_POST['RegisterForm'];
if($model->validate())
{
$user = new User;
$user->username = $_POST['RegisterForm']['username'];
$this->password = $_POST['RegisterForm']['password'];
$this->salt = Security::GenerateSalt(128);
$user->password = hash('sha512', $password.$salt);
$user->question = $_POST['RegisterForm']['question'];
$user->answer = $_POST['RegisterForm']['answer'];
$user->salt = $salt;
$user->email = $_POST['RegisterForm']['email'];
$user->fullname = $_POST['RegisterForm']['fullname'];
$user->birth = $_POST['RegisterForm']['dd'].'/'.$_POST['RegisterForm']['mm'].'/'.$_POST['RegisterForm']['yy'];
$user->avatar = CUploadedFile::getInstance($model,'image');
$user->about = $_POST['RegisterForm']['about'];
$user->sighnup = date('d/m/y');
$user->login = date('d/m/y');
if($user->save())
{
$model->image->saveAs('images/users/localFile.jpg');
// redirect to success page
}
$activation = new Activation;
$record = User::model()->findByAttributes(array('username'=>$_POST['RegisterForm']['username']));
$activation->user = $record->id;
$activation->code = Security::ActivationCode(32);
$activation->save();
}
}
$this->render('register',array('model'=>$model));
}
RegisterForm.php a verification model:
class RegisterForm extends CFormModel
{
public $username;
public $password;
public $password2;
public $question;
public $answer;
public $email;
public $fullname;
public $avatar;
public $about;
public $dd;
public $mm;
public $yy;
public $verifyCode;
public function rules()
{
return array(
array('username, password, password2, question, answer, email, fullname, dd, mm, yy', 'required'),
array('username','length','min'=>4),
array('username','length','max'=>16),
array('username', 'filter', 'filter'=>'strtolower'),
array('username', 'ext.alpha', 'allowSpaces'=>'flase', 'allowNumbers'=>'true', 'allAccentedLetters'=>'false'),
array('username', 'unique', 'attributeName'=> 'username', 'className'=>'User' ,'caseSensitive' => 'false'),
array('password', 'length', 'min' =>6),
array('password', 'length', 'max' =>32),
array('password2', 'compare', 'allowEmpty' => 'false', 'compareAttribute' => 'password'),
array('question', 'length', 'min' =>10),
array('question', 'length', 'max' =>128),
array('answer', 'length', 'min' =>4),
array('answer', 'length', 'max' =>64),
array('email', 'length', 'min' =>8),
array('email', 'length', 'max' =>128),
array('email', 'email'),
array('email', 'unique', 'attributeName'=> 'email', 'className'=>'User' ,'caseSensitive' => 'false'),
array('fullname','length','min'=>6),
array('fullname','length','max'=>64),
array('fullname', 'ext.alpha', 'allowNumbers'=>'false', 'allowSpaces'=>'true', 'allAccentedLetters'=>'false'),
array('avatar', 'file',
'types'=>'jpg, gif, png',
'maxSize'=>1024 * 1024 * 2,
'tooLarge'=>'The file was larger than 2MB. Please upload a smaller file.',
'wrongType'=>'Please upload only images in the format jpg, gif, png',
'tooMany'=>'You can upload only 1 avatar',
'on'=>'upload'),
array('about','length','max'=>384),
array('dd', 'numerical', 'allowEmpty'=>'false', 'integerOnly'=>'true', 'min'=>'1', 'max'=>'31'),
array('dd', 'FilterDay'),
array('mm', 'numerical', 'allowEmpty'=>'false', 'integerOnly'=>'true', 'min'=>'0', 'max'=>'12'),
array('mm', 'FilterMonth'),
array('yy', 'numerical', 'allowEmpty'=>'false', 'integerOnly'=>'true', 'min'=>'1900', 'max'=>'2008'),
array('yy', 'FilterYear'),
array('verifyCode', 'captcha', 'allowEmpty'=>!extension_loaded('gd')),
);
}
public function attributeLabels()
{
return array(
'username' => 'Username',
'password' => 'Passwrod',
'password2' => 'Verify Password',
'email' => 'Email',
'fullname' => 'Full Name',
'dd' => 'Day',
'mm' => 'Month',
'yy' => 'Year',
);
}
}
Register.php a view file:
<div class="form">
<h1><?php echo($data); ?></h1>
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'register-form',
'enableAjaxValidation'=>true,
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'username'); ?>
<?php echo $form->textField($model,'username'); ?>
<?php echo $form->error($model,'username'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'password'); ?>
<?php echo CHtml::activePasswordField($model,'password'); ?>
<?php echo $form->error($model,'password'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'password2'); ?>
<?php echo CHtml::activePasswordField($model,'password2'); ?>
<?php echo $form->error($model,'password2'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'email'); ?>
<?php echo $form->textField($model,'email'); ?>
<?php echo $form->error($model,'email'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'fullname'); ?>
<?php echo $form->textField($model,'fullname'); ?>
<?php echo $form->error($model,'fullname'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'question'); ?>
<?php echo $form->textField($model,'question'); ?>
<?php echo $form->error($model,'question'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'answer'); ?>
<?php echo $form->textField($model,'answer'); ?>
<?php echo $form->error($model,'answer'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'avatar'); ?>
<?php echo CHtml::activeFileField($model, 'avatar'); ?>
<?php echo $form->error($model,'avatar'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'about'); ?>
<?php echo CHtml::activeTextArea($model, 'about'); ?>
<?php echo $form->error($model,'about'); ?>
</div>
<?php
function getYear($value1 = 1900, $value2 = 2008)
{
$data = array();
for ($i = $value2; $i >= $value1; $i--){
$data[$i] = (string)$i;
}
return $data;
}
function getMonth()
{
$data = array();
for ($i = 1; $i <= 12; $i++){
$data[$i] = (string)$i;
}
return $data;
}
function getDays()
{
$data = array();
for ($i = 1; $i <= 31; $i++){
$data[$i] = (string)$i;
}
return $data;
}
?>
<div class="row">
<?php echo $form->labelEx($model,'dd'); ?>
<?php echo CHtml::activeDropDownList($model,'dd', getDays()); ?>
<?php echo $form->error($model,'dd'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'mm'); ?>
<?php echo CHtml::activeDropDownList($model,'mm', getMonth()); ?>
<?php echo $form->error($model,'mm'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'yy'); ?>
<?php echo CHtml::activeDropDownList($model,'yy', getYear()); ?>
<?php echo $form->error($model,'yy'); ?>
</div>
<?php if(extension_loaded('gd')): ?>
<div class="simple">
<?php echo CHtml::activeLabel($model,'verifyCode', array('style'=>'width:150px;')); ?>
<div>
<?php $this->widget('CCaptcha'); ?>
<?php echo CHtml::activeTextField($model,'verifyCode'); ?>
</div>
<p class="hint">Please enter the letters as they are shown in the image above.
<br/>Letters are not case-sensitive.</p>
</div>
<?php endif; ?>
<div class="row buttons">
<?php echo CHtml::submitButton('Submit'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
I am getting no errors at all but the fact is that there is no post in database at all, please help me
--------------------------------------------------------Edited---------------------------------------------------------------------
I found out what was the problem. the problem is that I can't insert an information in database via active record. When I type:
$user = new User;
$user->username = 'irakli';
$user->save();
it runs without errors but it doesn't insert anything in database. But the fact is that Database connection is active because I can read raws from database via Active Record, the problem is that I can't insert a new data in database via Active Record.
So any ideas?
Try this:
$user = new User;
$user->username = 'irakli';
if ($user->save())
{
echo "user record saved to the db";
}
else
{
var_dump($user->getErrors());
}

Categories