Is there a way to mingle validations in jQuery and CodeIgniter - codeigniter

If we want to include jQuery Validation plugin as well as code igniter form_validation class at once we have to define the validation rules in both jQuery validation script as well as in CodeIgniter form_validation. Is there a way to mingle both in a single call. Like, I want to define the validation rules only once either in jQuery or CodeIgniter
jQuery: http://docs.jquery.com/Plugins/Validation
CodeIgniter http://codeigniter.com/user_guide/libraries/form_validation.html
Process now:
//jQuery
$("#username").validate({
debug: true
})
Code igniter:
//Code igniter
$this->form_validation->set_rules('username', 'Username', 'callback_username_check');
1) Load library in your controller.
$this->load->library('jquery_validation');
2) Set CodeIgniter standard validation rules ( The same rules format which has form_validtion library ).
$rules = array(
array(
'field' => 'username',
'label' => 'Username',
'rules' => 'required|min_length[2]'
),
array(
'field' => 'email',
'label' => 'Email',
'rules' => 'required|valid_email'
),
array(
'field' => 'url',
'label' => 'URL',
'rules' => 'required'
)
);
3) Set error messages.
$messages = array(
'username' => array( 'required' => "Username is required",
'min_length' => "Please enter more then 2 char"
),
'email' => array( 'required' => "Email is required",
'valid_email' => "Please enter valid email"
)
);
4) Apply validation rules and messages to library.
$this->jquery_validation->set_rules($rules);
$this->jquery_validation->set_messages($messages);
5) Generate Javascript validation code.
// pass css selector for your form to run method
$validation_script = $this->jquery_validation->run('#registration_form');
// echo $validation_script in your <script> tag
This is the way to add jquery validation using code igniter validation definitions. My question is to get a validation library which uses this validation rule to both client side and server side validation.

jQuery validation happens in the client.
Codeigniter validation happens on the server.
They're COMPLETELY independent of one another. If you set your rules up correctly, Codeigniter validation will only even happen if jQuery validation doesn't happen for some reason.

Related

How to validate HTML response in post array in codeigniter

I am using tinymce for to add user cover letter related to the application.
This what my post array look like:
Array
(
[cover_letter] => <p>Test Cover Letter</p>
<ol>
<li>Need to save this data</li>
</ol>
<p><strong>Thanks</strong></p>
)
Simply I have used the require validation rule for this.
'candidate_cover_letter' => array(
array(
'field' => 'cover_letter',
'label' => 'Cover Letter',
'rules' => 'required'
)
)
I get the validation error regarding this like Cover Letter require.
I have two main problem:
How to validate HTML post array data
Is this best practice to save data like this? if no then how should i save this data?
First of all, in Codeigniter if we want to do form validations we need to go like this :
$config = array(
array(
'field' => 'username',
'label' => 'Username',
'rules' => 'required'
),
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'required',
'errors' => array(
'required' => 'You must provide a %s.',
),
)
);
$this->form_validation->set_rules($config);
You can refer here
so, your code here should be like this in the controller:
$config =array(
array(
'field' => 'cover_letter',
'label' => 'Cover Letter',
'rules' => 'required'
)
);
$this->form_validation->set_rules($config);
You can add extra fields in the $config like the example above.
Another thing that you asked, "How you should save the data ?"
I would suggest you to use a field in the database table with type "TEXT" and it should be okay for you.
After you hit submit you get redirected back to your controller somewhere. One way to utilize CI form validation is:
//look to see if you have post data
if($this->input->post('submit')){
//points to applications/config/form_validation.php (look at next chucnk to set form_validation.php)
if($this->_validate('cover_letter')){
//rest of your post logic
//get data to upload to database
$data = [
'cover_letter'=>$this->input->post('cover_letter'),
'user_id'=>$this->input->post('user_id')
];
//save data to database ..also this should be moved to a model
$this->db->insert('name of table to insert into', $data);
}
//if you post doesnt not get validated you will fall here and if you have this chucnk of code in the same place were you have the logic to set up the cover letter you will see a pink message that says what ever error message you set up
}
Set up form validation.php
<?php
$config = [
//set up cover letter validation
//$this->_validate('cover_letter') maps to here and checks this array
'cover_letter' => [
[
'field'=>'cover_letter',
'label'=>'Cover Letter Required',//error message to return back to user
'rules'=>'required'//field is required
],
//example to add additional fields to check
[
'field'=>'observations',
'label'=>'Observations',
'rules'=>'required'
],
],
]

CodeIgniter custom validation errors for each rule per each field

I'm using CodeIngiter 2.1 and I wanna define custom validation errors for each rule per each field. The fields are as follows.
array(
'field' => 'firstname',
'rules' => 'required',
'error' => 'This field cannot be empty.'
),
array(
'field' => 'email',
'rules' => 'required',
'error' => 'The email cannot be empty.'
)
But In CodeIgniter only one error message is defined for one rule. So how to override that one and Please suggest some solutions for getting different errors for perticular field. The work is more appreciated.
Try using the CI function :
set_message();
All of the native error messages are located in the following language file:
language/english/form_validation_lang.php
To set your own custom message you can either edit that file, or use the following function:
$this->form_validation->set_message('rule', 'Error Message');
for more about set_message here
Hope it will help;
I recently made this custom error message option for my codeigniter 3.0-dev applicaiton. Hope this helps anyone out there.
https://gist.github.com/abdmaster/7287962
To use it (example),
$this->form_validation->set_rules('name','Name','required|alpha',array('required' => 'Please fill the field %s .');`
It will work with Base models like jamierumbelow's MY_Model. In your model, you do something like this:
public $validate = array(
'display_name' => array(
'field' => 'display_name',
'label' => 'Display Name',
'rules' => 'trim|required|xss_clean|valid_fullname|is_unique[users_model.display_name]',
'error_msg' => array(
'is_unique' => 'The name in %s is already being used by someone.',
),
),
);
Rest are how we are use normally. Hope these examples are enough.
I haven't tried in v2.1.x but hopefully this will work. Maybe have to do some minor adjustments.

Needing different approach with validation rule for distinct actions in same Controller

I have a controle to handle some information that can be either saved or updated on DB.
I'm using public $validation to store an array with the validation rules that would look like this:
public $validation = array(
array(
'field' => 'modelname[column1]',
'label' => 'Column 1',
'rules' => 'required'
),
array(
'field' => 'modelname[column1]',
'label' => 'Column 2',
'rules' => 'required'
),
);
and I'm using my own validation function with callbacks in this same $validation. Like this:
array(
'field' => 'modelname[column3]',
'label' => 'Column 3',
'rules' => 'callback_column3|required'
),
array(
'field' => 'modelname[column4]',
'label' => 'Column4',
'rules' => 'callback_column4|required'
),
Which is handled with an action in the Controller.
The problem is that:
For add ( save ) I have to check the uniqueness of the value, that's the function of the callback_column4 ( let's say ) and if it's not unique it returns false. But, I can't return false for the edit (update) because I'm reading and editing something that's, obviously, in the DB.
So, what should I do to distinguish the two different action when validating.
PS: I have already tried to use subarrays with the Class/action ( http://codeigniter.com/user_guide/libraries/form_validation.html#savingtoconfig ) name but I'm using a Core_Model abstraction that plays the role of calling
$this->form_validation->set_rules($this->validation);
$this->form_validation->run()
You could add validation rules for that input in the controller method that is calling it rather than trying to put everything in the same array. That way you can keep your public validation var for all of the other rules but just set the one that is causing issues for you independently.
You could also create two separate arrays for your validation rules and call each one for its respective method. i.e.
$this->form_validation->set_rules($this->create_validation);
and
$this->form_validation->set_rules($this->edit_validation);

Codeigniter Custom Form Validation

this is my register method on controller to register a new user.
function register() {
$config_rules = array(
array(
'field' => 'txtEmail',
'label' => 'Email',
'rules' => 'required|valid_email'
),
array(
'field' => 'txtPassword',
'label' => 'Password',
'rules' => 'required|min_length[6]'
),
array(
'field' => 'txtRePassword',
'label' => 'Re-type Password',
'rules' => 'required|min_length[6]'
)
);
$this->form_validation->set_rules($config_rules);
if(isset($_POST['btnSubmit']) && $this->form_validation->run() == TRUE)
{
// insert query and redirect to registration success page
}
$this->load->view('users/register_form');
}
All the rules for form validation are work fine.
But, the problem is I can't do is to validate password and re-type password.
How make a custom form validation such as to check either
password and re-type password are same or not. Then return false for the validation and give error message telling that password and re-type password are not same through validation_errors().
You can specify the rule something like this:
$rules['password'] = "required|matches[passconf]";
In the above example, the field password will be matched with password confirm field passconf.
See the docs for more information.
http://ellislab.com/codeigniter/user-guide/libraries/form_validation.html
add:
matches[txtRePassword]
to the password rules, then you can use:
$this->validation->set_message('matches', 'New Passwords don\'t match');
to make a customer error message

cakePHP optional validation for file upload

How to make file uploading as optional with validation?
The code below validates even if i didn't selected any file.
I want to check the extension only if i selected the the file.
If i am not selecting any file it should not return any validation error.
class Catalog extends AppModel{
var $name = 'Catalog';
var $validate = array(
'name' => array(
'rule' => '/^[a-z0-9 ]{0,}$/i',
'allowEmpty' => false,
'message' => 'Invalid Catalog name'
),
'imageupload' => array(
'rule' => array('extension',array('jpeg','jpg','png','gif')),
'required' => false,
'allowEmpty' => true,
'message' => 'Invalid file'
),
);
}
thanks in advance
"I assign $this->data['Catalog']['image'] = $this->data['Catalog']['imageupload']['name'];"
So by the time you save your data array, it looks something like this I assume:
array(
'image' => 'foobar',
'imageupload' => array(
'name' => 'foobar',
'size' => 1234567,
'error' => 0,
...
)
)
Which means, the imageupload validation rule is trying to work on this data:
array(
'name' => 'foobar',
'size' => 1234567,
'error' => 0,
...
)
I.e. the value it's trying to validate is an array of stuff, not just a string. And that is unlikely to pass the specified validation rule. It's also probably never "empty".
Either you create a custom validation rule that can handle this array, or you need to do some more processing in the controller before you try to validate it.
Concept:
In Controller, before validating, or saving (which does validation automatically by default) check if any file is uploaded. If not uploaded, then unset validator for the file field.
Sample code:
Controller
// is any image uploaded?
$isNoFileUploaded = ($this->request->data['Model']['field_name']['error'] == UPLOAD_ERR_NO_FILE) ? true : false ;
if ($isNoFileUploaded) {
$this->Model->validator()->remove('field_name');
}
Notes:
This solution comes under preprocessing as one of the two alternative approaches (preprocessing in controller, custom validation in model) suggested by #deceze's answer

Resources