Codeigniter - checkbox form validation - php

I have a form validation rule in place for a form that has a number of checkboxes:
$this->form_validation->set_rules('groupcheck[]', 'groupcheck', 'required');
If none of my checkboxes are checked upon submission, my code never gets past the validation->run as the variable does not exist:
if ($this->form_validation->run()):
If i surround my validation rule with a check for the var, the validation never passes as there are no other form validation rules:
if(isset($_POST['groupcheck'])):
$this->form_validation->set_rules('groupcheck[]', 'groupcheck', 'required');
endif;
How can I manage a checkbox validation rule where the var may not exist, and it will be the only form variable?
Regards, Ben.

Don't use isset() in CodeIgniter as CodeIgniter provide better class to check if the POST Variable you are checking is exist or not for example try to use this code instead of your code:
if($this->input->post('groupcheck')):
$this->form_validation->set_rules('groupcheck[]', 'groupcheck', 'required');
endif;
For Guidline using on how to use POST and GET variables in CodeIgniter check the User Guide here: http://codeigniter.com/user_guide/libraries/input.html

I had the same issue.
If your checkbox is unchecked then it will never get posted. Remove the set_rules for your checkboxes and after your other form validation rules, try something like:
if ($this->form_validation->run() == TRUE){ // form validation passes
$my_checkbox_ticked = ($this->input->post('my_checkbox')) ? yes : no;

You may compare validation_errors() after $this->form_validation->run() if is FALSE then nothing was validate, so you can do something or show a warning
if ($this->form_validation->run() == FALSE) {
if (validation_errors()) {
echo validation_errors();
} else {
echo 'empty';
}
}

You also need to set button submit
$this->form_validation->set_rules('terminos_form', 'TERM', 'required');
$this->form_validation->set_rules('terminosbox', 'TERM BOX', 'callback__acept_term');
Callback
function _acept_term($str){
if ($str === '1'){
return TRUE;
}
$this->form_validation->set_message('_acept_term', 'Agree to the terms');
return FALSE;
}
HTML
<input type="checkbox" name="terminosbox" value="1"/>
<button type="submit" name="terminos_form" value="1">NEXT</buttom>

Related

best practice to post data on codeigniter controller with same url?

hello i have two route in codeigniter:
$route['register'] = 'Login/Register';
$route['login'] = 'Login/index';
for displaying login/register form
and form post routes:
$route['loginprocess'] = 'Login/LoginProcess';
$route['registerprocess'] = 'Login/RegisterProcess';
it's ok, but while using form_validation class in
$this->form_validation->set_error_delimiters('<span class="help-block">', '</span>');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
$this->form_validation->set_rules('pwd', 'Password', 'required');
if ($this->form_validation->run() == FALSE){
$this->load->view('login');
} else {
validation success
}
problem is when i get error in form validation it goes in
http://localhost/logincode/loginprocess
is so it's not url friendly. it should post in same controller method where form already display :
http://localhost/logincode/login
so is there any way to post form in same url. with form validation error comes together
Posting to Same URL in CodeIgniter
You've described a common scenario. You want to load a page with a form, perform a POST request, validate the request, then show errors if there is a problem. There are some potential issues to be aware of if you're doing this:
After a successful post, what happens if the browser performs a page refresh?
After a successful post, what happens if the user navigates away to another page, but then travels backwards in history?
Both of these issues present a duplicate post issue, and that's never desirable. The way to solve this is to use a form token. A form token is generated during the loading of the page where the form is present. The value is commonly a random string of characters, and it is put in two places:
In the form as a hidden form field.
In a session or cookie.
When the form is posted, the token value in the hidden form field is passed along with the rest of the posted data. Since there is a session or cookie containing the same value, the controller/method being posted to can check if they match, and if they do then validation can be performed, and errors or success message output. In any case, a new form token is generated, so two posts will never contain the same form token.
Summary of The Basic Concept
// You of course have to start the
// session for this to work.
$this->load->library('session');
if(
isset( $_POST['token'] ) &&
isset( $_SESSION['token'] ) &&
$_POST['token'] == $_SESSION['token']
){
// Do validation ...
// ...
// If validation passes
if( $this->form_validation->run() ){
$valid = TRUE;
}
// If there were validation errors
else{
$errors = validation_errors();
}
}
if( isset( $errors ) )
{
// Display the errors
}
if( isset( $valid ) )
{
// Display a thank you message
}
// Always refresh the token
$token = substr(md5(uniqid() . microtime() . rand()), 0, 8);
$_SESSION['token'] = $token;
?>
<form method="POST">
<input type="text" name="x" />
<input type="hidden" name="token" value="<?php echo $token; ?>" />
<input type="submit" value="submit" />
</form>
In practice this concept of tokens can be much more elaborate. For instance, you may choose to encrypt the token values and then decrypt them when checking if they match. You might also create an array of tokens in your session/cookie, and check your posted token against the array of tokens. You may have other ideas on how to customize form tokens, but the basics have been presented here, and I hope it helps you achieve your goal of posting to the same URL in CodeIgniter.

How to set default values for CodeIgniter Form Validation?

I know to use set_value() for setting default values in a CodeIgniter form, but how can I set the default values for the validation if either the value isnt submitted or its before a form submission?
public function index($uri = NULL)
{
$this->load->helper('form');
$this->load->library('form_validation');
//pull from DB or Session
$data = array(
'Status' => 'users_default_status',
'Order' => 'users_default_order',
'Asc' => 'users_default_asc'
);
$this->form_validation->set_data($data);
$this->form_validation->set_rules('Status', 'Status', 'numeric|trim|required|strtolower');
$this->form_validation->set_rules('Order', 'Order', 'trim|required');
$this->form_validation->set_rules('Asc', 'Asc', 'trim|required|strtolower');
if ($this->form_validation->run() === FALSE) // validation failed
{
// validation failed but maintain submitted values in form/feedback
}else{
// validation successful, do whatever
}
}
So that if there was a form submission it uses the POST values, and if not it uses defaults (but still validated). I would like the defaults to work on a variable by variable basis, so some can be defaults some can be user submitted.
I know to use set_value() for setting default values in a CodeIgniter form, but how can I set the default values for the validation if either the value isn't submitted or it's before a form submission?
Simply check if the value exists and use it as the default, otherwise it's blank (or a different default).
In the Controller, decide if you're going to load a blank form, if not, send the data for the fields....
$data['fieldname'] = "whatever"; // from the database
$this->load->view('yourpage', $data);
Then in your View, check for the existence of this data for each field. If the data was sent, use it. Otherwise, set a blank value.
<?php $value = isset($fieldname) ? $fieldname : ''; ?>
<input name="fieldname" value="<?php echo set_value('fieldname', $value); ?>" type="text" />
If you do not send the data from the Controller, the field will be blank (you could also set a default)
If you send the data from the Controller, the field will be filled out with this data from your Controller (database).
If you submit the form and validation fails, set_value() function will reload the field with the data from the most recent post array.
These are just some thoughts...
The validation rules act upon the posted data. So if you are using set_value('order',$default_order), when the form is submitted it will either take the new user entered value or the one you provided.
If the user empties a prefilled or default input, you can't have it set as "required" in the rules. What you would do is use a callback function to handle that case to check if it's empty and provide a default value and return TRUE.

code igniter form validation returns false even if data is entered

I am setting new rules to my form, and even if the form fields are not empty, I still get stuck into the validation check block
validation function:
if (isset($_POST['action']) && $this->input->post('action') === "add_category") {
echo "<pre>";
print_r($_POST);
$this->form_validation->set_rules($this->input->post('cat_name'), 'Category Name', 'required');
if ($this->form_validation->run() === FALSE) {
echo "false";
exit;
}
else {
echo "true" ; exit;
}
}
output
Array
(
[action] => add_category
[cat_name_] => gbddbd
[parent_cat] => 1
[cat_status] => 1
)
false
I creating simple HTML forms in my view, not with the help of CI form helpers
there is a mistake in how you use set_rules()
the correct way would be:
$this->form_validation->set_rules('cat_name','Category Name', 'required')
explanation: the first parameter of set_rules() indicates the name of the input field you are validating. In your code, you are trying to assign the value of the input field, instead of the name
You are setting rule for "cat_name" and the form field is "cat_name_" so it is failing. Change your form field name to "cat_name"

More than one form validation run statement

I want to get two form validation run statement in my project.First I want to check my select box value. If its space, then I am getting an error message. Here I also want to get a validation if the select box value is 'Other', Then I want to check the value in the text box. Is it possible.
Ie, I want to execute two form validation run statement.If first run statement is true, I have to check with the second run statement.
There is no reason you can't set some rules, run validation, then set some more rules and then run validation again.
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'required');
if ($this->form_validation->run() == FALSE) {
// Do whatever you do on fail
} else {
$this->form_validation->set_rules('email', 'Email', 'required');
if ($this->form_validation->run() == FALSE) {
// do whatever you do on the 2nd fail
}
// do whatever you do on success
}

Is there a way to disallow word in Codeigniter's built in form validation?

O have a form that the fields are prefilled by jQuery. When a user clicks in the field, the field empties itself, and they type their information. However if they don enter information in each filed the default value is submitted. I would like to use Codeigniter's built in validation to disallow users creating an account with a first name of "First Name".
See here: otis.team2648.com/auth/register
Thanks,
Blake
You can use a callback function:
// your rules
$this->form_validation->set_rules('first_name', 'required|callback__no_first_name');
// callback
function _no_first_name($str) {
if ($str !== 'First Name') {
return TRUE;
}
else
{
$this->form_validation->set_message('_no_first_name', 'You should not have "First Name as the first name"');
return FALSE;
}
}
I would extend the Form_validation library and turn it into a more valuable form validation rule that you could reuse easily...
example - (Change relevant info for your version of CI)
class MY_Form_validation extends CI_Form_validation {
function __construct() {
parent::CI_Form_validation();
}
function disallow_string($str,$word)
{
return ( strpos($str,$word) === FALSE ) ? TRUE : TRUE;
}
}
Place above code in MY_Form_Validation.php in application/libraries
and in your validation, just use the rule like this
$this->form_validation->set_rules('first_name', 'required|disallow_string[First Name]');
note that you can then use this same rule for all fields, as other uses I can envision.
Don't write the default text as value in the field! Use this construction:
<input type="text" name="uname" id="uname" placeholder="Your name" />
If the user set the focus on this field, the text disappears. But no value is submitted if the user insert nothing.

Categories