I have built a Login form under PHP Codeigniter framework and its validation rules are set.
The rules are working fine, but what I want to achieve is something different.
The login form has Username & Password Textbox set under a container called control-group.
Those who uses Bootstrap framework for HTML, knows this very well.
So the textbox code is like this :
<div class="control-group">
<label for="username">Username:</label>
<input type="text" id="username" name="username" value="" placeholder="Username" class="login username-field" />
<?php echo form_error('username','<span class="help-inline error">', '</span>'); ?>
</div>
You can see I have also placed span wrappers to error, so that it can be displayed in red color style. But what other thing I want to do is, I want to apply the error class to the control-group.
So that it become from
<div class="control-group">
To
<div class="control-group error">
I have already tried this by taking $error_class variable and passing it from Controller like this.
$data['error_class'] = '';
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
if ($this->form_validation->run() == FALSE){
$data['error_class'] = 'error';
$this->load->view('administrator/login_view', $data);
}
But what it does is, it applied the error class to the control-group all the time. Even without submitting the form.
Any idea how to achieve this ?
Thanks in advance.
You have to run the validation only when the user is submitting the form.
try doing this
if($this->input->post())
{
//your form validation
}
This will only run when user submits a post request.
EDIT:
In addition to populate error on each individual field, use form_error('field_name') to check for error in each individual fields and echo the error class
eg.
<?=(form_error('field_name')?'error':'')?>
Related
I'm using codeigniter 3.1.9 to create a login form using a html helper and form_validation library for its validation.
For validating the input fields i'm using set_rules('input name, 'relative name', 'required') function in the controller and for displaying the errors i'm using validation_errors('your div for showing the errors') function in the view.
Also i'm using set_value('input name') function for setting their input values but i'm unable to see the success message that i have passed from the controller and also the validation errors doesn't seem to go after i hit the submit button which exists on top right after the form tag even if the input fields are not empty.
Please find the link for the screenshot of the source code below and provide me any solution to indentify the actual problem with the code. Thank you
Link to see the source code of the controller & view
Used two same attributes in the input field of your form which is not correct.
Form validation is run by the name attribute.
Removing them will correct the form validation
Login Controller
class Login extends CI_Controller {
public function index()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('user_email', 'Username', 'required');
$this->form_validation->set_rules('user_pass', 'Password', 'required');
if ($this->form_validation->run() == FALSE) {
$this->load->view('login');
} else {
echo "Form Submit.";
}
}
}
View File
<?php echo form_open(); ?>
<?php echo validation_errors('<div class="error">', '</div>'); ?>
<input type="text" name="user_email" value="<?php echo set_value('user_email'); ?>">
<input type="password"" name="user_pass" value="<?php echo set_value('user_pass'); ?>">
<input type="submit" value="Login">
<?php echo form_close(); ?>
once again I'm lost. I'm gonna start ahead with the issue, because I am not even sure what I really want.
Example:
I have an article view. The URL is: http://index.php/news/article/3
This actually runs the article($id) function in my news controller and gives it the 3 as an argument. The function then fetches the article information and displays it in the view.
On the article page, the user can also log in. Logging in is triggered on pressing
submit button inside my form form_open('core/login')...button...</form> In the function I log the user in and refresh the current view with some elements changed according to the user being logged. The problem is that the URL is now http://index.php/core/login. Obviously I would like it to be the original URL.
Is there any, possibly simple, solution to achieve this? Thank you all for reading and in advance for your replies.
Difficult without more code but let me give you my theory / take on this:
Default controller:
User is not logged in - show default header, content, footer
User presses login, form is shown
User is authenticated - yes (continue) no (go back to form)
User is redirect('home')'d
Your default controller/home controller checks if auth'd: if authorised then show logged in header, content and logged in footer
or simply pass 'loggedIN' as a $data['loggedIN'] variable to the view - but this breaks the ideology of MVC framework.
More info from you and I can be more specific, or we can talk on IRC.
Adding this code from a controller i'm working on right this minute - I use ion_auth library (you should look it up, it's excellent).
This is my default controller - and as you can see some simple logic loads the different views/states.
public function index(){
if ($this->data['auth_login'] ) {
/*is already signed in so just present the lobby?*/
$data['page_title'] = "HN Lobby";
$data['menuItems'] = nav_anchor_helper_authd();
$data['myUserID'] = $this->ion_auth->get_user_id();
$data['lobby_players'] = $this->lobby_model->get_players();
$this->load->view('template/public/header',$data);
$this->load->view('player_pages/nav_2',$data);
$this->load->view('player_pages/lobby',$data);
$this->load->view('template/scripts/main',$data);/*scraper and other scripts*/
$this->load->view('template/public/footer',$data);
} else {
/*request login*/
$data['page_title'] = "PLAY HN";
$data['menuItems'] = nav_anchor_helper();
$data['auth_rtnurl'] = current_url();
$data['auth_conturl'] = current_url(); /*for now just come back to same page where lobby should load - perhaps in future a semi gooey login? e.g where was user going - this could be the continue url in this var right here << */
$data['message_body'] = $this->session->flashdata('message');
$this->load->view('template/public/header',$data);
$this->load->view('template/public/nav_1',$data);
$this->load->view('public_pages/play',$data);
$this->load->view('template/public/footer',$data);
}
}
Here is how I handle the return URL in my login function:
Login/auth controller: (using ion_auth)
function login()
{
$this->data['title'] = "Login";
//validate form input
$this->form_validation->set_rules('identity', 'Identity', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
if ($this->form_validation->run() == true)
{
if ($this->ion_auth->login($this->input->post('identity'), $this->input->post('password'), $remember))
{
//if the login is successful
//redirect them back to the home page
$this->session->set_flashdata('message', $this->ion_auth->messages());
$rtnurl = $this->input->post('auth_conturl');
if(!$rtnurl || $rtnurl == ""){
$rtnurl = '/';
}
redirect($rtnurl, 'refresh');
}
This is only an extract/segment of the login function - but as you can see i utilise the function 'redirect' from code igniter to push the user back to the return URL posted with the login form (which was set in the view/previous controller using the current_url() function.
Finally my default view file with login form to show you how i am passing the return url:
<div>
<h4>Login</h4>
<div id="infoMessage" class="errortext"><?php echo $message_body;?></div>
<?php echo form_open('auth/login', array('class' => 'form col')); ?>
<p>
<label for="identity">Email:</label> <input type="text" name="identity" value="" id="identity"> </p>
<p>
<label for="password">Password:</label> <input type="password" name="password" value="" id="password"> </p>
<p>
<label for="remember">Remember Me:</label> <input type="checkbox" name="remember" value="1" id="remember"> </p>
<p><input type="submit" name="submit" value="Login ยป"></p>
<p>
Forgot password ?
</p>
<input type="hidden" name="auth_rtnurl" value="<?php echo $auth_rtnurl; ?>"/>
<input type="hidden" name="auth_conturl" value="<?php echo $auth_conturl; ?>"/>
<?php echo form_close();?>
</div>
To use the current dynamic url as form action, just use -
<?= form_open(current_url()); ?>
I've checked and re-checked my code, referencing the CI docs and other posts throughout the web, but I am unsuccessful at implementing the set_value() method for re-populating form fields after failed validation.
Perhaps I am missing something very fundamental to the CI framework (I'm rather new to it), but your insight would be much appreciated.
I have the following in my controller method:
public function form_step2(){
//Form Setup
$this->load->helper('form');
$this->load->helper('url');
$this->load->library('form_validation');
$data['title'] = $this->base_title;
$data['base_url'] = base_url();
//Validation Settings - must be set per step
$this->form_validation->set_rules('request_type', 'Request Type', 'required');
*...more of the same set_rules()*
if ($this->form_validation->run() === FALSE) {
### Validation failed or New Form
// Get form element data
$data['request_types'] = $this->my_model->get_form_data('request_type');
*...more of the same get_form_data() calls for loading form elements*
//Generate Page from View Templates
$this->load->view('templates/header', $data);
$this->load->view('templates/form_step2', $data);
$this->load->view('templates/footer');
} else {
### Save to database
$this->my_model->set_data($data);
redirect('my_model/success','refresh');
}
}
And in my view, a snippet of the code that is not re-populating:
<?php echo form_open('my_model/form_step2', array('class'=>'form-inline')); ?>
<label for="fname">First Name</label>
<input type="text" id="fname" name="fname" value="<?php echo set_value('fname'); ?>" />
<input type="submit" name="submit" value="Submit" />
I can't figure this one out, so thanks in advance for your help.
if you want to use set_data() you need to also use set_rules for that POST/GET field.
Since you've commented out all your set_rules I can not confirm that this is the issue but most likely it is.
please check if you have this line in your code
$this->form_validation->set_rules('fname', 'First name', 'trim|required');
So if you want to re-populate field with name="fname" you need to have set_rules() // as line above for it otherwise it won't process therefore set_value('fname') is empty.
you surely have found a solution but, for people like me which were spending too many time for this trouble.
I found a solution:
so instead to code that
<input type="text" id="fname" name="fname" value="<?php echo set_value('fname'); ?>" />
Try this, it run very well:
<?php $data = array('id' =>fnam, 'name'=> 'fname','value'=> set_value('fname'), 'size =>'50');
echo form_input($data).'<br />'; ?>
Try this way. It will get both validation errors and set value
In View
<?php echo flash_message();
if($this->session->userdata('postinput') !=""){
$value = $this->session->userdata('postinput');
$this->session->unset_userdata('postinput');
}else
$value = "";
?>
<form action="<?php echo site_url('carlisting/carlist');?>" method="post" id="your_reg_form">
<div class="reg-search">
<input placeholder="YOUR REG" name="input" type="text" value="<?php echo $value; ?>">
</div>
In Controller
$this->form_validation->set_rules('input', 'Registration', 'required|min_length[2]|max_length[7]');
if ($this->form_validation->run() == false){
$this->session->set_flashdata( 'message', array('content' => validation_errors(), 'type' => 'error_message_small' ));
$this->session->set_userdata('postinput',$this->input->post('input'));
redirect('home');
}
Permits you to set the value of an input form or textarea. You must supply the field name via the first parameter of the function. The second (optional) parameter allows you to set a default value for the form. Example:
<input type="text" name="quantity" value="<?php echo set_value('quantity', '0'); ?>" size="50" />
The above form will show "0" when loaded for the first time.
I am new to PHP Codeigniter framework. I am designing a page in which I am using a link. On clicking the link it is calling a jquery function, which submits form through jquery. I have used codeigniter form validation methods for server side validation and for the timebeing I have disabled the client side validation.
The problem is that in this process when the form is submitted through jquery, the codeigniter form validation method is not working.
But if I am using a submit button to submit the form then the codeigniter form validation method works perfectly.
Please advise me what to do if I need to submit the form through jquery and use the codeigniter form validation method.
Please find the code below:
Login Form:
<?php echo validation_errors(); ?>
<form name="login-form" id="login-form" method="post" action="<?php echo base_url();?>index.php/login/login_form" >
<H2>Login</H2>
<div id="login-box-name">
Email:
</div>
<div id="login-box-field">
<input name="user-name" id="user-name" class="form-login" title="Please Enter Correct User Name" value="" size="30" maxlength="2048" />
</div>
<div id="login-box-name">
Password:
</div>
<div id="login-box-field">
<input name="password" id="password" type="password" class="form-login" title="Please Enter Correct Password" value="" size="30" maxlength="2048" />
</div>
<br />
<span class="login-box-options">
<input type="checkbox" name="1" value="1" title="Want this computer to remember you!!"> Remember Me Forgot password?
</span>
<br />
<br />
<a href="" id="login-submit">
<img src="<?php echo base_url();?>assets/images/login-btn.png" width="110" height="40" style="margin-left:90px;" />
</a>
<input type="submit" name="submit" id="submit" value="Submit" />
</form>
jquery function to submit the form on clicking the "link":
$("#login-submit").click(function()
{
$('#login-form').submit();
return false;
});
Controller function:
public function login_form()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$data['title'] = 'Log In';
$data['errorMessage'] = '';
$this->form_validation->set_rules('user-name', 'Email', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('templates/header', $data);
$this->load->view('login', $data);
$this->load->view('templates/footer');
}
else
{
$this->load->view('templates/header', $data);
$this->load->view('templates/menu');
$this->load->view('index', $data);
$this->load->view('templates/footer');
}
}
Here if I click on the "Submit button of the form, then the codeigniter validation works for user-name and password fields. But if I click the link with id="login-submit", then it calls the jquery function and the form get submitted. But the codeigniter validation does not work for user-name and password fields this time.
I need to submit the form through the link and the codeigniter validation function should work for this.
Thanks in Advance.....
Use .preventDefault() instead of just returning false on the anchor click event.
This has happened to me before and it seems to me that there is a conflict somewhere using .submit() inside a click event and returning false to stop the anchor's default behavior.
The code above is working fine. Actually I made a silly mistake in my code.
I used following code for jQuery and it is working now.
$("#login-submit").click(function(e) {
e.preventDefault();
$('#login-form').submit();
});
Thanks
it happens because it calls the function all the time when clicking on the button. you need to stop that.
$("#login-submit").click(function(e){
e.preventDefault();
$('#login-form').submit();
});
I want to submit this form through PHP. with validation for required field and validation for phone number and email field also
<form action="" method="" id="get-protected">
<div class="row requiredRow">
<label for="txt_FirstName">
First Name</label>
<input id="txt_FirstName" type="text" class="required" title="First Name. This is a required field" />
</div>
<div class="row">
<label for="txt_LastName">
Last Name</label>
<input id="txt_LastName" type="text" title="First Name. This is a required field" />
</div>
<div class="row">
<label for="txt_Phone">
Phone</label>
<input id="txt_Phone" type="text" title="First Name. This is a required field" />
</div>
<div class="row requiredRow">
<label for="txt_Email">
Email</label>
<input id="txt_Email" type="text" class="required" title="Email. This is a required field" />
</div>
<div class="row">
<input type="submit" value="" class="button" />
</div>
</form>
In your method attribute inside your form, you need to declare either post or get.
Since your action attribute is "" it will submit to the page itself rather than redirecting to another page, so you can have your code that checks for validation in the same PHP file. First validation that is often checked is if the variable has a value by using isset:
if(isset($_POST['txt_Phone'])) { ... }
This just checks that the Phone number field does not contain empty data. I strongly suggest you perform other validation checks on the POST array so you do not have any users posting malicious code.
You can use functions like htmlspecialchars to prevent user-supplied text depending on what you plan to do with the values
Here are some references to help you along the way in the order they should be viewed.
Form Validation using PHP - PHP and MySQL Tutorial
PHP Advance Form Validation Tutorial
PHP Tutorial Part 2: Form Validation
Your form tag needs a target in the action field and a method in the method field (either GET or POST). So make the action your PHP script.
<form name="input" action="form_submit.php" method="get">
As for field validation, you will either have to parse that inside of the PHP and return a response or use Javascript in the browser to check on the fly.
Here is the shcema of such a script:
if ($_SERVER['REQUEST_METHOD']=='POST') {
//data validation:
$err="";
if (valid_phone($_POST['phone'])) $err="Wrong phone no";
if (!$err) {
//record data:
$sql="...";
query($sql);
Header("Location: ".$_SERVER['REQUEST_URI']); //redirect and exit
exit;
}
}
?>
<html>
<head></head>
<body>
<? if ($err) ?> <font color=red><b><?=$err?></b></font>
<form method="POST" id="get-protected">
here goes your form
Okay, firstly, I like to set the form action to <?=$_SERVER['REQUEST_URI']?> to submit it back to the current page, but leaving it as you have it will work fine too.
Secondly, you need to give all your <input>s a name attribute. This is the variable name that PHP will see.
When your users get an error (something doesn't validate correctly) you don't want all the data they entered to disappear. That means you have to set the value attributes of each input to what they had previously entered. Thus, your form starts to look like this:
<form action="<?=$_SERVER['REQUEST_URI']?>" method="" id="get-protected">
<div class="row requiredRow">
<label for="txt_FirstName">
First Name</label>
<input id="txt_FirstName" type="text" class="required" title="First Name. This is a required field" name="first_name" value="<?=htmlspecialchars($_POST['first_name'])?>" />
</div>
...
<div class="row">
<input type="submit" name="submit" value="" class="button" />
</div>
</form>
If you didn't know <?= is a basically a shortcut for <?php echo but it will only work if your server has short tags enabled. Some people prefer to type it out the long way (in case they want to switch servers later, or for future-compatibility, or because they're nutbars), but I say screw them, I'm lazy.
This page that has the form on it, has to saved with a .php extension (well, technically it doesn't have to, but that's another story). Then you need to handle you form validation. You have to code that up yourself. It might look something like this (put it above your form somewhere)
<?php
if($_POST['submit']) {
$errors = array()
if(empty($_POST['first_name'])) $errors[] = 'please enter your first name';
if(empty($errors)) {
// save the data to database or do whatever you want with it
header('redirect:succcess.php');
} else {
foreach($errors as $e) {
echo $e;
}
}
}
?>
It's been a while since I've coded in PHP so forgive me if there are syntax errors. That's the jist of it anyway, I'm sure you can find validation libraries out there if you Google. Might take some of the grunt work out of trying to validate email addresses and such.
Using Javascript you can do the validation for this form.For each condition you can use return true and return false,based on the condition.Then you can submit the value.
Using action attribute in form tag the values will be submitted to that file.