简体   繁体   中英

Use codeigniter Form validation lib. to validate arrays not from post

Might be a duplicate. but i couldnt find anything on google so here we Go.

i have a form that submit data. this data is further process and split it into variables.

example

My form post <input name='cmd' value='create -u username@demo.com -p password'/>

so i receive such post and split it into

$username=username@demo.com
$password=password

now i want to validate these variables, since form_validation lib. is already there so why not use it !. i know i can use preg_match. but i think there i no need to reinvent what already there , a

$this->form_validation->set_rules($username, 'username', 'required|xss_clean');
$this->form_validation->set_rules($password, 'username', 'required|xss_clean');

Would be a beautiful approach.

is there a way i can tweak CI form validation to accept variable instead of field_name ? may be a helper function would be great for this matter. that can even use $$variable to id name of variable for rules like match[] validation.

thanks a lot and i hope i explained my question well.

There are 2 ways to accomplish what you need, one is defining your input fields and do the split on the client side like:

<form method="post">
  <input id="cmd" value="<?php if (set_value('username')) : ?>create -u <?=set_value('username')?> -p <?=set_value('password')?><?php endif; ?>"/>
  <input type="hidden" name="username" value="<?=set_value('username')?>" />
  <input type="hidden" name="password" value="<?=set_value('password')?>" />
</form>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"/>
<script type="text/javascript">
$(function () {
    $('#cmd').change(function () {
        var matches = $(this).val().match(/create -u ([^\b]+) -p ([^\b]+)\]/);
        $('input[name=username]').val(matches[1]);
        $('input[name=password]').val(matches[2]);
    });
});
</script>

Or you simply validate with a callback like:

<form method="post">
  <input name="cmd" value="<?=set_value('cmd')?>"/>
</form>

$this->form_validation->set_rules('cmd', 'Command', 'required|callback_validate_cmd');

function validate_cmd($cmd)
{
    if ($cmd) {
        list($username, $password) = split_cmd($cmd);
        $this->load->helper('security');
        if ( ! xss_clean($username)) {
            $this->form_validation->set_message(__FUNCTION__, 'username_not_secure');
            return FALSE;
        } elseif ( ! xss_clean($password)) {
            $this->form_validation->set_message(__FUNCTION__, 'password_not_secure');ç
            return FALSE;
        }
    }
    return TRUE;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM