Why isn't my CodeIgniter Form Validation working? - php

I am trying to set up validation on a simple contact form that is created using the form helper. No validation at all occurs. What is wrong?
In the code below, the “good” keyword always shows, regardless of what is entered into the form, and the saved values set via set_value are never shown.
Controller
// Contact
function contact() {
$data['pageTitle'] = "Contact";
$data['bodyId'] = "contact";
$this->load->library('form_validation');
$config_rules = array ('email' => 'required','message' => 'required');
$this->form_validation->set_rules($config_rules);
if ($this->form_validation->run() == FALSE) {
echo "bad";
$data['include'] = "v_contact";
$this->load->view('v_template',$data);
} else {
echo "good";
$data['include'] = "v_contact";
$this->load->view('v_template',$data);
}
}
View
echo validation_errors();
echo form_open('events/contact');
// name
echo form_label('Name', 'name');
$data = array (
'name' => 'name',
'id' => 'name',
'maxlength' => '64',
'size' => '40',
'value' => set_value('name')
);
echo form_input($data) . "\n<br />";
// email address
echo form_label('Email Address', 'email');
$data = array (
'name' => 'email',
'id' => 'email',
'maxlength' => '64',
'size' => '40',
'value' => set_value('email')
);
echo form_input($data) . "\n<br />";
// message
echo form_label('Message', 'message');
$data = array (
'name' => 'message',
'id' => 'message',
'rows' => '8',
'cols' => '35',
'value' => set_value('message')
);
echo form_textarea($data) . "\n<br />";
echo form_submit('mysubmit', 'Send Message');
echo form_close();

It looks like you're not setting the validation rules according to the way the new Form_validation library does it (the user guide has a section on the new syntax). That seems to be the syntax for the old Validation library.
Try this instead for your $config_rules array and see if your validation runs properly:
$config_rules = array(
array('field' => 'email', 'rules' => 'required'),
array('field' => 'message', 'rules' => 'required')
);
$this->form_validation->set_rules($config_rules);

Related

How to send validation error massage? Codeigniter

I want to display validation error msg on registration form. Msg should be displayed when Login already exist in database.
MY error: Unable to access an error message corresponding to your field name Login_r.(rule)
Pleas try to help me, its very important. Thank you
config/form_validation.php
$config = array(
'login' => array(
array(
'field' => 'login',
'label' => 'Login',
'rules' => 'required'
),
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'required'
)
),
'register' => array(
array(
'field' => 'name_r',
'label' => 'Name',
'rules' => 'required|alpha'
),
array(
'field' => 'lastname_r',
'label' => 'Lastname',
'rules' => 'required|alpha'
),
array(
'field' => 'login_r',
'label' => 'Login_r',
'rules' => 'required|callback_rule'
),
array(
'field' => 'password_r',
'label' => 'Password_r',
'rules' => 'required|min_length[4]|max_length[12]'
),
array(
'field' => 'confirm_password_r',
'label' => 'Confirm_password',
'rules' => 'required|matches[password_r]'
),
array(
'field' => 'email_r',
'label' => 'Email',
'rules' => 'required|valid_email'
),
array(
'field' => 'adres_r',
'label' => 'Adres',
'rules' => 'required'
)
),
);
Controller:
if ($this->form_validation->run('register') == false)
{
$this->form_validation->set_message('rule', 'Dzialaj !');
$this->load->view('content/register');
}
else
{
$this->load->view('content/index');
$name_r = $this->input->post('name_r');
$lastname_r = $this->input->post('lastname_r');
$login_r = $this->input->post('login_r');
$password_r = $this->input->post('password_r');
$email_r = $this->input->post('email_r');
$adres_r = $this->input->post('adres_r');
$data_db = array(
'name' => $name_r,
'lastname' => $lastname_r,
'login' => $login_r,
'password' => $password_r,
'email' => $email_r,
'adres' => $adres_r
);
$this->Main_model->register($data_db);
}
Model:
public function register($data_db) {
$this->db->where('login',$data_db['login']);
$query = $this->db->get('users');
$row = $query->row();
if($row->login){
$this->form_validation->set_message('rule', 'Error Message');
} else {
$this->db->insert('users', $data_db);
}
View(forms)
<?php
echo validation_errors();
echo form_open();
echo 'Imie: ' . form_input('name_r');
echo br(2);
echo 'Nazwisko: ' . form_input('lastname_r');
echo br(2);
echo 'Login: ' . form_input('login_r');
echo br(2);
echo 'Haslo: ' . form_password('password_r');
echo br(2);
echo 'Potwierdz Haslo: ' . form_password('confirm_password_r');
echo br(2);
echo 'E-mail: ' . form_input('email_r');
echo br(2);
echo 'Adres: ' . form_input('adres_r');
echo br(1);
echo form_submit('zarejestrowany','Stworz konto');
echo form_close();
?>
</div>
</div>
</div>
<!--Import jQuery before materialize.js-->
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script type="text/javascript" src="js/materialize.min.js"></script>
</body>
</html>
I'm not sure where you have your validation code you posted, that should be in the controller too. I'd suggest refactoring so you don't do any validation in the model:
Model:
public function get_user($login) {
$this->db->where('login',$login);
$query = $this->db->get('users');
$row = $query->row();
return $row;
}
public function register($data_db) {
$this->db->insert('users', $data_db);
}
Controller:
if ($this->form_validation->run('register') == false)
{
$this->form_validation->set_message('rule', 'Dzialaj !');
$this->load->view('content/register');
}
else
{
$this->load->view('content/index');
$name_r = $this->input->post('name_r');
$lastname_r = $this->input->post('lastname_r');
$login_r = $this->input->post('login_r');
$password_r = $this->input->post('password_r');
$email_r = $this->input->post('email_r');
$adres_r = $this->input->post('adres_r');
$user = $this->Main_model->get_user();
if($user->login) {
$this->form_validation->set_message('rule', 'Error Message');
redirect('content/register')
}
$data_db = array(
'name' => $name_r,
'lastname' => $lastname_r,
'login' => $login_r,
'password' => $password_r,
'email' => $email_r,
'adres' => $adres_r
);
$this->Main_model->register($data_db);
This still isn't great since I have to use a redirect if it $user->login is true, it would be even better to create the callback like I mentioned in the chat, but I don't really understand how your code is structured.
Your controller needs a function called "rule" (because you have a rule called "callback_rule" in your form_validation rules).
function rule($form_value)
{
if(<condition for form value is good>)
{
return TRUE;
}
else
{
$this->form_validation->set_message('login_r','your error message');
return FALSE;
}
}

Index value is also shown with database value

I have dropdown with database values.But,dropdown also shows database value's index and i want to remove index.I have searched in google and other forums,but not getting expected solution.
function products_edit($product_id) {
$this->load->helper('form');
$this->load->helper('html');
$this->load->library('form_validation');
$this->load->model('products_model');
$data=$this->products_model->general();
$category['categories']=$this->products_model->get_category();
$product = $this->products_model->get_product($product_id);
$this->data['title'] = 'Edit Product';
//validate form input
$this->form_validation->set_rules('name', 'Product name', 'required|xss_clean');
$this->form_validation->set_rules('description', 'Product Description', 'required|xss_clean');
$this->form_validation->set_rules('category', 'Category', 'required|xss_clean');
//$this->form_validation->set_rules('extras', 'Extras', 'required|xss_clean');
$this->form_validation->set_rules('price', 'Price', 'required|xss_clean');
$this->form_validation->set_rules('is_featured', 'Is Featured', 'required|xss_clean');
$this->form_validation->set_rules('prorder', 'prorder', 'required|xss_clean');
if (isset($_POST) && !empty($_POST)) {
$data = array(
'product_name'=> $this->input->post('name'),
'product_desc'=> $this->input->post('description'),
'product_category' => $this->input->post('category'),
'extras' => $this->input->post('extras'),
'price' => $this->input->post('price'),
'is_featured' => $this->input->post('is_featured'),
'prorder' => $this->input->post('prorder'),
);
if ($this->form_validation->run() === true) {
$this->products_model->updateproducts($product_id, $data);
$this->session->set_flashdata('message', "<p>Product updated successfully.</p>");
redirect('products_controller/products_edit/'.$product_id);
}
}
$this->data['message'] = (validation_errors() ? validation_errors() : $this->session->flashdata('message'));
$this->data['product'] = $product;
//display the edit product form
$this->data['name'] = array(
'name' => 'name',
'id' => 'name',
'type' => 'text',
'style' => 'width:300px;',
'value' => $this->form_validation->set_value('name', $product['product_name']),
);
$this->data['description'] = array(
'name' => 'description',
'id' => 'description',
'type' => 'text',
'cols' => 60,
'rows' => 5,
'value' => $this->form_validation->set_value('description', $product['product_desc']),
);
$cat=array();
$test = array();
for($i=0;$i<=3;$i++) {
$test[$i] = array($category['categories'][$i] => $category['categories'][$i]);
}
$this->data['category'] = $test;
$this->data['extras'] = array(
'name' => 'extras',
'id' => 'extras',
'type' => 'text',
'style' => 'width:250px;',
'value' => $this->form_validation->set_value('extras', $product['extras']),
);
$this->data['price'] = array(
'name' => 'price',
'id' => 'picture',
'type' => 'text',
'style' => 'width:250px;',
'value' => $this->form_validation->set_value('price', $product['price']),
);
$this->data['is_featured'] = array(
'name' => 'is_featured',
'id' => 'is_featured',
'type' => 'text',
'style' => 'width:250px;',
'value' => $this->form_validation->set_value('is_featured', $product['is_featured']),
);
$this->data['prorder'] = array(
'name' => 'prorder',
'id' => 'prorder',
'type' => 'text',
'style' => 'width:250px;',
'value' => $this->form_validation->set_value('prorder', $product['prorder']),
);
$this->load->view('products_edit', $this->data);
}
The error occurs in this line.
for($i=0;$i<=3;$i++) {
$test[$i] = array($category['categories'][$i] => $category['categories'][$i]);
}
The error is due to $i in the test array. If I remove it, causing an error. I don't have solution for this error.
The screen shot http://i.share.pho.to/f4a24cc3_o.png
Is there a particular reason why you're using a for loop to build your categories dropdown list?
The $test array needs to look something like this:
$test = array(
1 => 'Pizza',
2 => 'Sandwich',
3 => 'Dessert',
4 => 'Salad'
);
Where the key is the associated id to the category and the value is the category name. At the minute you are loading both the key and value of the array with the whole category (based on it's index).
If you are wanting to pull out all the categories into a dropdown box, I would suggest something similar to the below, as this would allow you to add additional categories in future and them appear in the dropdown box:
foreach($category['categories'] as $category) {
$test[$category['id']] = $category['name'];
}
$this->data['category'] = $test;
This would require the categories (which I assume are being pulled out of a database table?) to have an id and name field.
Hope that helps...

Formatting form error messages

Form code :
$this->add(array(
'name' => 'username',
'type' => 'Text',
'options' => array(
'label' => 'Username',
),
));
model :
$inputFilter->add(array(
'name' => 'username',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'NotEmpty',
'options' => array(
'messages' => array(
\Zend\Validator\NotEmpty::IS_EMPTY => 'Username required',
),
),
),
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 5,
'max' => 69,
),
),
),
));
View :
$form->setAttribute('action', $this->url('signup', array('action' => 'signup')));
$form->prepare();
echo $this->form()->openTag($form);
echo $this->formRow($form->get('username'));
then I get output like following :
It seems every individual part of ‘Zend\Validator’ works alone and throws error message individually. I want to display the required message only if the field is empty, not the stringlength. How can I do that ?
-Thanks.
Update :
I did the following in the 'view' page :
echo $this->formRow($form->get('username'));
foreach($form->getMessages() as $key=>$value){
if($key=="username"){
if(isset($value['isEmpty'])){
echo $value['isEmpty'];
}else if(isset($value['stringLengthTooShort'])){
echo $value['stringLengthTooShort'];
}else if(isset($value['stringLengthTooLong'])){
echo $value['stringLengthTooLong'];
}
}
}
then got the output :
now there are two error messages in unordered list still being there. how can I remove those messages and keep my formatted message only ?
Solved :
I had to do the following :
View :
$errmsg = $form->getMessages();
echo $this->formLabel($form->get('username'));
echo $this->formInput($form->get('username'));
if ($errmsg) {
if (isset($errmsg['username'])) {
foreach ($errmsg['username'] as $key => $value) {
?>
<span class="formerror">
<?php
if ($key == "isEmpty") {
echo $value;
break;
} else if ($key == "stringLengthTooShort") {
echo $value;
break;
} else if ($key == "stringLengthTooLong") {
echo $value;
break;
}
?>
</span>
To format the error messages I can’t use ‘formelementerrors’ because it returns string (ref: http://framework.zend.com/manual/2.0/en/modules/zend.form.view.helpers.html#formelementerrors), not array. so its easy to identify individual errors by keys if I use ‘getMessages()’.
In your controller you can use this method for retrieve the errors messages :
$form->getMessages();
Is an array and you can use a foreach to retrieve the key 'isEmpty' and display this.

Show the correct error validation messages

I have a page with 2 forms on it: a registration form and a login form. Each form has a submit button. Now I'm validating both forms, but for example if I press the submit button of the registration form I'd like only to show the error messages of the registration form and not of the login form. At the moment both error message are being shown. Is there a way around this?
<div class="grid-container">
<div class="grid-50 login">
<h3>Inloggen</h3>
<?php
$loginEmail = array('placeholder' => "Email", 'name' => "loginEmail");
$loginPassword = array('placeholder' => "Wachtwoord", 'name' => "loginPassword");
$loginSubmit = array('name' => "loginSubmit", 'class' => "btn", 'value' => "Inloggen");
$loginForgot = array('name' => "loginForgot", 'class' => "link", 'value' => "Wachtwoord vergeten?");
echo form_open('login/inloggen', array('class' => 'grid-100 formc'));
echo form_input($loginEmail);
echo form_password($loginPassword);
echo form_submit($loginSubmit);
echo form_submit($loginForgot);
echo form_close();
?>
<?php echo validation_errors('<p class="error">');?>
</div>
<div class="grid-50 login">
<h3>Registreren</h3>
<?php
$registerName = array('placeholder' => "Naam", 'name' => "registerName");
$registerEmail = array('placeholder' => "Email", 'name' => "registerEmail");
$registerPassword = array( 'placeholder' => "Wachtwoord", 'name' => "registerPassword");
$registerSubmit = array('name' => "registerSubmit", 'class' => "btn", 'value' => "Registreer");
echo form_open('login/register');
echo form_input($registerName, set_value('registerName'));
echo form_input($registerEmail, set_value('registerEmail'));
echo form_password($registerPassword);
echo form_submit($registerSubmit);
echo form_close();
?>
<?php echo validation_errors('<p class="error">');?>
</div>
Validation in the controller
$this->form_validation->set_rules('registerEmail', 'Email verkeerd', 'trim|required|valid_email');
$this->form_validation->set_rules('registerPassword', 'Password te kort', 'trim|required|min_length[4]');
it would be nicer if you create different rules for the login and for you're registration.
how?
create a Form_validation.php file on application/libraries
inside specify the rules for you're login and register example
$config = array(
'login_validation_rules'=>array(
array(
'field' => 'username',
'label' => 'The User Name',
'rules' => 'required'
),
array(
'field' => 'password',
'label' => 'The Password',
'rules' => 'required'
)
),
'registration_validation_rules'=>array(
array(
'field' => 'email',
'label' => 'The Email',
'rules' => 'required|valid_email'
),
array(
'field' => 'firstname',
'label' => 'The Firstname',
'rules' => 'required'
)
)
);
Then on you're controller you can catch what form they are submitting and what validation rules to use example
if($this->input->post('registerSubmit'))
{
if($this->form_validation->run('registration_validation_rules') == FALSE)
{
//error
}else{
//good
}
}elseif($this->input->post('loginSubmit')){
if($this->form_validation->run('login_validation_rules') == FALSE)
{
//error
}else{
//good
}
}
At the same time you're controller will not be cluttered with rules. makes reading easier you can read more of this on the Codigniter manual - validation config file
Do you use two submit in one page? try to make one to submit through javascript or jquery
be cause when you submit the submit it submit the whole page in some browsers
also try this show validate error for each fields
<?=form_error('loginEmail')?>
<?=form_error('registerPassword')?>

Form validation not working in CodeIgniter, controller issue

I have a controller and a view. I am trying to submit some details through a form, but when I submit it, no errors are displayed.
I am using only one controller to for 2 different types of users. The two users are -
User
Gym/Health Club Owner
And according to the $suertype, I have the same view being called but a different content being loaded.
This is my controller:
public function CreateProfile_Step2()
{
$data['page_title'] = 'Create Profile (Step 2)';
$loginid = $this->session->userdata('loginid');
$this->load->model('profilemodel', 'profile');
$userid = $this->profile->get_userid($loginid);
$this->session->set_userdata('userid', $userid);
$usertype = $this->profile->get_usertype($userid);
$data['usertype'] = $usertype;
if ($usertype == 'User') {
$this->load->model('activitymodel', 'activity');
$arr_activities = $this->activity->get_activities();
$data['options'] = $arr_activities;
}
else if ($usertype == 'Gym/Health Club Owner') {
$this->load->model('facilitymodel', 'facility');
$arr_facility = $this->facility->get_facilities();
$data['options'] = $arr_facility;
}
$config = array(
'User' => array(
array(
'name' => 'sex',
'label' => 'Sex',
'rules' => 'required'
)),
'Gym/Health Club Owner' => array(
array(
'name' => 'website',
'label' => 'Website',
'rules' => 'prep_url'
),
array(
'name' => 'hours_of_operation',
'label' => 'Hours of Operation',
'rules' => 'required|numeric'
),
array(
'name' => 'membership_charges',
'label' => 'Membership Charges',
'rules' => 'required|numeric'
))
);
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
$this->form_validation->set_rules($config);
if ($usertype == 'User') {
if ($this->form_validation->run('User') == FALSE) {
$this->load->view('create-profile-step-2', $data);
}
else {
$selected_options = $this->input->post('activities');
$this->activity->add_user_activities($userid, $selected_options);
$sex = $this->input->post('sex');
$this->profile->add_user_details($userid, $sex);
echo 'Profile Creation Completed!';
}
}
else {
if ($this->form_validation->run('Gym/Health Club Owner') == FALSE) {
$this->load->view('create-profile-step-2', $data);
}
else {
$selected_options = $this->input->post('facilities');
$this->facility->add_gym_facility($userid, $selected_options);
$website = $this->input->post('website');
$hours_of_operation = $this->input->post('hours_of_operation');
$membership_charges = $this->input->post('membership_charges');
$this->facility->add_gym_details($userid, $website, $hours_of_operation, $membership_charges);
echo 'Profile Creation Completed!';
}
}
}
This is my view:
<?php include 'user/inc/header.php'; ?>
<div id="content" class="row twelvecol">
<h1>Create Profile (Step 2 of 2)</h1>
<h2>For <?php echo $usertype; ?></h2>
<?php
echo form_open('register/CreateProfile_Step2');
if ($usertype == 'User') {
echo form_label('Sex', 'sex');
$options_sex = array(
'Male' => 'Male',
'Female' => 'Female'
);
echo form_dropdown('sex', $options_sex, 'male');
$ctr = 1;
echo form_label('Activities Interested In', 'activities');
foreach($options->result() as $option)
{
echo form_label($option->activity, 'activity-'.$ctr);
$arr_option = array(
'name' => 'activities[]',
'id' => 'activity-'.$ctr++,
'value' => $option->activity
);
echo form_checkbox($arr_option);
}
}
elseif ($usertype == 'Gym/Health Club Owner')
{
echo form_label('Website', 'website');
$arr_website = array(
'name' => 'website',
'id' => 'website',
'value' => set_value('website')
);
echo form_input($arr_website);
echo form_label('Hours of Operation', 'hours_of_operation');
$arr_hours = array(
'name' => 'hours_of_operation',
'id' => 'hours_of_operation',
'value' => set_value('hours_of_operation')
);
echo form_input($arr_hours);
echo form_label('Membership Charges', 'membership_charges');
$arr_charges = array(
'name' => 'membership_charges',
'id' => 'membership_charges',
'value' => set_value('membership_charges')
);
echo form_input($arr_charges);
$ctr = 1;
echo form_label('Facilities Available', 'facilities');
foreach($options->result() as $option)
{
echo form_label($option->facility, 'facility-'.$ctr);
$arr_option = array(
'name' => 'facilities[]',
'id' => 'facility-'.$ctr++,
'value' => $option->facility
);
echo form_checkbox($arr_option);
}
}
echo "<br/><br/>";
echo form_submit('submit', 'Create Profile');
echo form_close();
echo validation_errors();
?>
Return to previous step
</div>
<?php include 'user/inc/footer.php'; ?>
It's more likely some problem with the $config, because I have tried changing my code and used 2 separate controllers and views for the 2 cases.
Well, since no one answered my question. I was going through the code and found the errors myself. I had used the key 'name' in my configuration instead of 'field'.
INCORRECT CODE
$config = array(
'User' => array(
array(
'name' => 'sex',
'label' => 'Sex',
'rules' => 'required'
)),
'Gym/Health Club Owner' => array(
array(
'name' => 'website',
'label' => 'Website',
'rules' => 'prep_url'
),
array(
'name' => 'hours_of_operation',
'label' => 'Hours of Operation',
'rules' => 'required|numeric'
),
array(
'name' => 'membership_charges',
'label' => 'Membership Charges',
'rules' => 'required|numeric'
))
);
CORRECT CODE
$config = array(
'User' => array(
array(
'field' => 'sex',
'label' => 'Sex',
'rules' => 'required'
)),
'Gym/Health Club Owner' => array(
array(
'field' => 'website',
'label' => 'Website',
'rules' => 'prep_url'
),
array(
'field' => 'hours_of_operation',
'label' => 'Hours of Operation',
'rules' => 'required|numeric'
),
array(
'field' => 'membership_charges',
'label' => 'Membership Charges',
'rules' => 'required|numeric'
))
);

Categories