More than one form validation run statement - php

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
}

Related

CI Form Validation of Date. with input type="date"

validating a form with that has an input type="date" which takes input mm/dd/yyyy
however if i var_dump the results it comes out as yyyy-mm-dd.
1 do I validate the input type "mm/dd/yyyy", or do i validate "yyyy-mm-dd".
---im assuming I validate what the var_dump gives me which is yyyy-mm-dd.
2 More importantly I am having a hard time finding out the simplest way of going about validating date.
---I am not sure how to go about validating the date without going through by hand and checking every single date. Is there some built in functions that I could use, and how would I go about implementing that in with my CI form validations I already have.
function check_registration($post_data)
{
// Validations:
// first_name
$this->form_validation->set_rules('first_name', 'First Name', "trim|required");
// last_name
$this->form_validation->set_rules('last_name', 'Last Name', "trim|required");
// email
$this->form_validation->set_rules('email', 'Email', "trim|required|valid_email|is_unique[users.email]");
// password
$this->form_validation->set_rules('password', 'Password', "trim|required|min_length[6]");
// confirm_password
$this->form_validation->set_rules('confirm_password', 'Confirm Password', "trim|required|matches[password]");
// DOB
$this->form_validation->set_rules('DOB', 'Date of Birth', "trim|required");
// run validations:
if ($this->form_validation->run() === False)
{
// set flash data errors
$this->session->set_flashdata("reg_first_name_error", form_error('first_name'));
$this->session->set_flashdata("reg_last_name_error", form_error('last_name'));
$this->session->set_flashdata("reg_email_error", form_error('email'));
$this->session->set_flashdata("reg_password_error", form_error('password'));
$this->session->set_flashdata("reg_confirm_password_error", form_error('confirm_password'));
$this->session->set_flashdata("reg_DOB_error", form_error('DOB'));
redirect('/');
}
// No errors:
else
{
$this->insert($post_data);
redirect('/success');
}
}
Thanks in advance.
-Ants
Set your own callback rule
$this->form_validation->set_rules('DOB', 'Date of Birth', "trim|required|callback_dob_check");
Write the function inside same controller. Date validation idea taken from: Using filter_var() to verify date?.
public function dob_check($str){
if (!DateTime::createFromFormat('Y-m-d', $str)) { //yes it's YYYY-MM-DD
$this->form_validation->set_message('dob_check', 'The {field} has not a valid date format');
return FALSE;
} else {
return TRUE;
}
}
More info on DateTime:createFromFormat http://php.net/manual/en/datetime.createfromformat.php. I would stick to YYYY-MM-DD format, as it's quite often.

Codeigniter - form validation 2 field required with not match value

I'm trying to make a validation for 2 field that must have a different value. I only know how to set the rules for validate matching value.
$this->form_validation->set_rules('book1','Book1','required|matches[book2]');
$this->form_validation->set_rules('book2','Book2','required|matches[book1]');
if I input book1=novel, and book2=novel, the code above will return TRUE.
How can I validate 2 field where the value of each field is not matching each other? So if I input book1=novel and book2=comic, it will return TRUE.
You should use callback_ method for custom validation, CI form validation library does not provide notMatch type validation rule, see below sample code.
$this->form_validation->set_rules('book1','Book1','required');
$this->form_validation->set_rules('book2','Book2','required|callback__notMatch[book1]');
AND place method in controller class
function _notMatch($book2Value, $book1FieldName){
if($book2Value != $this->input->post($book1FieldName){
$this->form_validation->set_message('_notMatch', 'book1 and book2 values are not matching');
return false;
}
return true;
}
In codeigniter 3 you can use the differs[] set rule, to enforce that field values don't match.
$this->form_validation->set_rules('book1', 'Book 1', 'required|differs[book2]');
$this->form_validation->set_rules('book2', 'Book 2', 'required|differs[book1]');
This means you don't need to create an unnecessary callback. However, for older versions you will.
See the documentations for more: Codeigniter 3 Documentation
You can use differs like so:
$this->form_validation->set_rules('password', 'current password', 'max_length[25]|min_length[5]|required');
$this->form_validation->set_rules('new_password', 'new password', 'max_length[25]|min_length[5]|required|differs[password]');
$this->form_validation->set_rules('confirm_password', 'confirm password', 'required|max_length[25]|min_length[5]|matches[new_password]');

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"

Unable to access an error message corresponding to your field name

I have a callback function that check_captcha which sees if $row is ==0 or == 1 (this information is queried from sql).
The problem is that I can not call it from $self->form_validation->set_rule('captcha', 'call_back_check_captcha') due to the fact that my function takes in a $row var. The way I'm calling it now I get a Unable to access error message. How can I make this work?
function check_captcha( $row)
{
if($row ==0)//didnt find any
{
$this->form_validation->set_message('captcha', 'text dont match captcha');
return FALSE;
}
else
{
return TRUE;
}
}
function create_member()
{
$past = time() - 7200;
$this->db->query("DELETE FROM captcha WHERE captcha_time <".$past);
$sql = "SELECT COUNT(*) AS count FROM captcha WHERE word =? AND ip_address =?";
$binds = array($_POST['captcha'], $this->input->ip_address(), $past);
$query= $this->db->query($sql, $binds);
$row = $query->row(); //row query rows : if it found an entry =1
$self->check_captcha($row->count);
//VALIDATIONS
$this->form_validation->set_rules('first_name', 'First Name', 'trim|required');
$this->form_validation->set_rules('last_name', 'Last Name', 'trim|required');
$this->form_validation->set_rules( 'email_address', 'Email Address', 'trim|required|valid_email|unique[user.email_address]');
$this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[4]|unique[user.username]');
$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[4]|max_leng[32]');
$this->form_validation->set_rules('password2', 'Password Confirmation','trim|required|matches[password]');
if(!$_POST['captcha']){
$this->form_validation->set_rules('captcha', 'Captcha','trim|required');}else{
$this->form_validation->set_rules('captcha', 'Captcha', 'callback_check_captcha');}
if($this->form_validation->run()==FALSE)
{ //this -> to the curr obj(UserController) && registraion() points to the the function in controller
$this->registration(); //reloads reg page so they can fill out right stuff
}
else
$this->form_validation->set_message('check_captcha', 'text dont match captcha');
The message name corresponds to the function, not the field. So setting it to "check_captcha" will fix your bug. The error message will use the correct field name.
Actually the best way, instead of write the error message directly on controller, would be add this entry "check_captcha" on languages.
In my case, the message for validation rule (form validation) "less_than" was not present.
I changed the file /system/language/??/form_validation_lang.php. I've added the missing entry.
That helped me
go to application/config/autoload.php and add "Security" helper class there.
$autoload['helper'] = array('security');
Or add this before your form validation
$this->load->helper('security');
You can set error message in set_rules :
$this->form_validation->set_rules('captcha', 'Captcha', 'callback_check_captcha',
array('check_captcha' => 'text dont match captcha'));
add a entry to your language file with named of the part inside the (yourfieldname) of the errormessage - thats solved the problem
Even if the question is already answered, there is another error that can lead to the same error message:
If you call your callback checkCaptcha, it will not work. Prefer always a name like check_captcha as recommended in Codeigniter/General Topics/PHP style guide.

Codeigniter - checkbox form validation

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>

Categories