[英]CodeIgniter Form_Validation without actual form
我想做的很简单(我希望):
我正在尝试使用Form_Validation验证POST数据(或任何通过variable提供的数据)。
问题是要运行实际验证,我/我们需要做
if ($this->form_validation->run() == FALSE){
//validation did not pass
}else{
//validation did pass
}
我的一套规则是这样的:
$this->form_validation->set_rules('key', '', 'trim|required'); //simplified
所以,我显然是通过AJAX将数据发送到此脚本的
echo $_POST['key']; //prints valid value that is sent from AJAX
如何使用form_validation验证$ _POST ['key']?
AJAX代码
$("#key-inputs .short, #key-inputs .long").change(function () {
var key = $(this).val();
var id = $(this).attr('name');
var table = $(this).attr('class');
var file = $('span .file').val();
var data = 'NULL';
$.post(file + "/edit",{
id:id,
key:key,
file:file,
table:table},
function(code, textStatus) {
data = code;
});
$(this).ajaxStop(function(){
if (data == 3) $(this).parent().fadeOut('slow', function() {}); //delete
if (data == 2) $(this).fadeOut(200).fadeIn(200); //update
if (data == 5) alert('not valid'); //update parameter is not valid input (depends on set_value rules)
//writeConsole(previous.val().outerHTML);
});
});
PHP代码//简化
if (!$this->input->is_ajax_request()) redirect('lang/translate/keys/'.$param);
//do work here
if ($key == "") {
//delete key
$this->lang_translate_model->DeleteKey($id, $table);
echo 3;
return TRUE;
}
$this->form_validation->set_rules('key', 'key', 'trim|required|max_length[56]|xss_clean|unique_file[lang_key:'.$param.']');
if ($this->form_validation->run() == FALSE){
//validation did not pass
echo 5;
}
所以我有一些(生成的)输入,关于更改,我只想在..set_rules通过的情况下才能在数据库中进行更新。
如果输入为空,则会删除自身(可以正常工作)
解
TRUE / FALSE表在这里
if ($this->form_validation->required($key)){
//validation did not pass
echo 5;
}
如果有参数要传递,例如min_length[2]
;
$this->form_validation->min_length($key,'2');
这取决于您使用的codeigniter的版本
codeigniter 3.0:
您可以使用set_data方法来验证您的自定义数据
$data = array(
'username' => 'johndoe',
'password' => 'mypassword',
'passconf' => 'mypassword'
);
$this->form_validation->set_data($data);
codeigniter 2.X:
手动设置$_POST
值
$_POST'username'] = 'johndoe';
$_POST['password'] ='mypassword';
$_POST['passconf'] = 'mypassword';
常见的:
对于共同的部分,值得庆幸的是他们仍然仍然使用form_validation->run()
和form_validation->set_rules(<SPECIFIC ATTRIBUTE RULES>)
看到这个 。 另外,请查看该页面下方的注释。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.