Codeigniter use form validation for variable - php

I've read somewhere that is possible to use Codeigniter's Form Validation also for my own variables and not only for form's inputs.
For example I'd like to validate a url to say if it is valid but not retrieving it using POST or GET from a form.
Do you know how or have a link?

What you are looking for are the callbacks of the Form Validation Class in CodeIgniter - read the user guide for an in-depth explanation.

For PHP5 above version,you can do this
function validdate_urls($str) {
if(!filter_var($str, FILTER_VALIDATE_URL))
{
$this->validation->set_message('validate_urls', 'URL Invalid');
return 0;
}else {
return TRUE;
}
}
And call it in your validation rules :-
$rules['link'] = "callback_validate_urls";

Yes you can via set_data() method, Here you go.
$this->form_validation->set_data(array(
'cartId' => $cartId
));
$this->form_validation->set_rules('cartId', 'Card ID', 'trim|required|is_natural_no_zero');
if ($this->form_validation->run() == FALSE) {
echo 'Invalid: ' . validation_errors();
} else {
echo 'Valid';
}

Related

form validation with preg_match in callback not working

I have questions about my codeigniter form validation. I try to validate the input form for name so it will generate error if user using symbol like ">?<*&%^$". Here is my code:
My rules:
$this->load->library('form_validation');
$this->form_validation->set_rules('full_name', 'Name', 'trim|required|callback_name_check',
array(
'name_check' => '%s should not using symbols'
)
);
This is my callback function (I tried to modify this from the last example I saw, so I thought the problem was here)
public function password_check($str)
{
if (preg_match('#[<>?&%$##]#', $str)) {
return TRUE;
}
return FALSE;
}
I have tried another example from another StackOverflow answer to use / as delimiter (like this --> [/<>?&%$##/]), but still, doesn't work. I'll appreciate your help sensei :)
Validation should be
$this->load->library('form_validation');
$this->form_validation->set_rules('full_name', 'Name', 'trim|required|callback_name_check');
Inside call back function
public function name_check($str)
{
if (preg_match('#[<>?&%$##]#', $str)) {
{
return TRUE;
}
else
{
#adding new validation error should be
$this->form_validation->set_message('full_name', '%s should not using symbols'); # input field name should come to first
return FALSE;
}
}
Note: Didn't validate REGEX which you have posted

Codeigniter: Array Submission Validation

I am having a problem on validating using empty() on codeigniter.
It seemed that it always returns true, empty or not.
<input type="text" name="contactname[]" value="<?php echo set_value('contactname[]');?>">
Model:
if(empty($this->input->post('contactname'))) {
return TRUE;
} else {
return FALSE;
}
I really don't know what's the cause of this issue.
try this
$contactname = $this->input->post('contactname')
if(empty($contactname)) {
return TRUE;
} else {
return FALSE;
}
CodeIgniter provides a comprehensive form validation and data prepping class that helps minimize the amount of code you'll write. You can load library like this in your controller or model :
$this->load->library('form_validation');
To set validation rules you will use the set_rules() function like this :
$this->form_validation->set_rules('contactname[]', 'Contact name', 'required');
So you need to update your code with given below code -
$this->load->library('form_validation');
$this->form_validation->set_rules('contactname[]', 'Contact name', 'required');
if ($this->form_validation->run() == FALSE)
{
echo validation_errors();
}
else
{
// wrire you code here after validation run success
}
For for reference see this link -
http://www.codeigniter.com/userguide2/libraries/form_validation.html
try this
$contact_name = $this->input->post('contactname[]');
if($contact_name != null)
{
return TRUE;
} else{
return FALSE;
}
Try this.
if (count($this->input->post('contactname')) > 0)
return TRUE;
} else {
return FALSE;
}

Validation Parameter Get Method in fuelphp

i have a problem when i want to validate using GET Method in fuelphp
i'm looking up in this documentation
// run validation on just post
if ($val->run())
{
// process your stuff when validation succeeds
}
else
{
// validation failed
}
that's code only validate if the method is Post or default post.
how to validate method get?
To run the validation against an array:
if ($val->run( array( $validation_rule => $value_to_validate) ))
{
// process your stuff when validation succeeds
}
else
{
// validation failed
}
Example:
$val = Validation::factory();
$val->add('email')->add_rule('valid_email');
if ($val->run( array('email'=>$email) ))
{
// $email is valid
}
else
{
// $email is not valid
}

codeigniter form callback value

Im carrying out some form validation with codeigniter using a custom validation callback.
$this->form_validation->set_rules('testPost', 'test', 'callback_myTest');
The callback runs in a model and works as expected if the return value is TRUE or FALSE. However the docs also say you can return a string of your choice.
For example if I have a date which is validated, but then in the same function the format of the date is changed how would I return and retrieve this new formatted value back in my controller?
Thanks for reading and appreiate the help.
I'm not entirely sure I got what you were asking, but here's an attempt.
You could define a function within the constructor that serves as the callback, and from within that function use your model. Something like this:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Controllername extends CI_Controller {
private $processedValue;
public function index()
{
$this->form_validation->set_rules('testpost','test','callback');
if ($this->form_validation->run()) {
//validation successful
echo $this->processedValue; //outputs the value returned by the model
} else {
//validation failed
}
}
private function callback($input)
{
$this->load->model('yourmodel');
$return = $this->yourmodel->doStuff($input);
//now you have the user's input in $input
// and the returned value in $return
//do some checks and return true/false
$this->processedValue = $return;
}
}
public function myTest($data){ // as the callback made by "callback_myTest"
// Do your stuff here
if(condition failed)
{
$this->form_validation->set_message('myTest', "Your string message");
return false;
}
else
{
return true;
}
}
Please try this one.
I looked at function _execute in file Form_validation of codeigniter. It sets var $_field_data to the result of callback gets(If the result is not boolean). There is another function "set_value". Use it with the parameter which is name of your field e.g. set_value('testPost') and see if you can get the result.
The way Tank_Auth does this in a controller is like so
$this->form_validation->set_rules('login', 'Login', 'trim|required|xss_clean');
if ($this->form_validation->run()) {
// validation ok
$this->form_validation->set_value('login')
}
Using the set_value method of form_validation is undocumented however I believe this is how they get the processed value of login after it has been trimmed and cleaned.
I don't really like the idea of having to setup a new variable to store this value directly from the custom validation function.
edit: sorry, misunderstood the question. Use a custom callback, perhaps. Or use the php $_POST collection (skipping codeigniter)...apologies haven't tested, but I hope someone can build on this...
eg:
function _is_startdate_first($str)
{
$str= do something to $str;
or
$_POST['myinput'} = do something to $str;
}
================
This is how I rename my custom callbacks:
$this->form_validation->set_message('_is_startdate_first', 'The start date must be first');
.....
Separately, here's the callback function:
function _is_startdate_first($str)
{
$startdate = new DateTime($this->input->post('startdate'), new DateTimeZone($this->tank_auth->timezone()));
$enddate = new DateTime($this->input->post('enddate'), new DateTimeZone($this->tank_auth->timezone()));
if ($startdate>$enddate) {
return false;
} else {
return true;
}
}

Validating forms with regex in codeigniter

How can I validate a form using regex in codeiginiter. I'd like to check the input against:
^([0-1][0-9]|[2][0-3]):([0-5][0-9])$
I'm assuming the best way is in some sort of callback. I tried a bunch of ideas on the web but I can't seem to get any working.
Old post but you can add the regex directly in the input validation rule
$this->form_validation->set_rules()
Add to function above: regex_match[your regex]
You can create a function like this:
function validateRegex($input)
{
if (preg_match('/^([0-1][0-9]|[2][0-3]):([0-5][0-9])$/', $input))
{
return true; // it matched, return true or false if you want opposite
}
else
{
return false;
}
}
In your controller, you can use it like:
if ($this->validateRegex($this->input->post('some_data')))
{
// true, proceed with rest of the code.....
}
How about using AJAX?
$("form").submit(function(e) {
e.preventDefault();
$.post("<?php echo base_url(); ?>regex_check", { username: $("#username").val() }, function (data) {
alert(data);
});
The regex_check function would have a typical regex check in it, like
function regex_check(){
$this->get->post('username');
if(eregi('^[a-zA-Z0-9._-]+#[a-zA-Z0-9-] +\.[a-zA-Z.]{2,5}$', $username)){
return TRUE;}else{return FALSE;}
}
You would only allow successful submission of form if all data is validated.
These code snippets should help you on the track to validating the data.
here's a full solution submitting to account/signup
in the account controller:
function signup(){
if($_POST){
$this->form_validation->set_rules('full_name', 'Full Name', 'required|min_length[3]|max_length[100]');
$this->form_validation->set_rules('email_address', 'Email Address', 'required|valid_email');
$this->form_validation->set_rules('password', 'Password', 'required|callback_check_password');
if ($this->form_validation->run() == FALSE){
echo validation_errors();
}
else{
// form validates, now can do stuff such as insert into database
// and show the user that they successfully signed up, i.e.,:
// $this->load->view('account/signup_success');
}
}
}
check_password callback function also in the account controller:
function check_password($p){
$p = $this->input->post('password');
if (preg_match('/(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8}/', $p)) return true;
// it matched, see <ul> below for interpreting this regex
else{
$this->form_validation->set_message('check_password',
'<span class="error">
<ul id="passwordError">
<li> Password must be at least:</li>
<li> 8 characters</li>
<li> 1 upper, 1 lower case letter</li>
<li> 1 number</li>
</ul>
</span>');
return false;
}
}

Categories