- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我的表单验证规则有问题(在单独的配置文件中)。这发生在复选框中。
为了组织我的验证规则,我创建了一个名为 validation_rules
的库文件。该库包含我所有的自定义回调,例如 valid_date
等。为了能够调用这些规则,我加载了该库,然后使用以下配置:
array(
'field' => 'terms',
'label' => 'lang:reg_lbl_terms',
'rules' => array(array('terms_accepted', array($ci->validation_rules, 'terms_accepted')))
),
其中 $ci
是对 CodeIgniter ($this
) 的引用。
现在这适用于大多数类型的输入,但它不适用于留空的复选框,可能是因为它们没有被发布。
但是,当我放弃我的库并简单地将回调添加到 Controller 时,使用以下配置一切正常:
array(
'field' => 'terms',
'label' => 'lang:reg_lbl_terms',
'rules' => array('callback_terms_accepted')
),
此外,当我在 rules
数组(或字符串)中的任何位置添加规则 required
时,required
规则会被调用(返回false,因为未选中该复选框),但所有其他规则将被完全忽略。
这一定是 CodeIgniter 中的错误吧?有人有解决方案或解决方法吗?当然this是一个选项,但我真的不喜欢它。
相关文档:http://www.codeigniter.com/user_guide/libraries/form_validation.html
编辑:复选框 PHP/HTML:
<?php
$data = array(
'name' => 'terms',
'value' => 'true'
);
echo form_checkbox($data);
// Results in: <input type="checkbox" name="terms" value="true">
// No set_value() is used.
?>
最佳答案
您可以在/config 内的 form_validation 文件中创建规则
$config = array(
'controller/method' => array(
array('field'=>'', 'label'=>'', 'rules'=>'required|acceptTerms')
array('field'=>'another', 'label'=>'', 'rules'=>'required')
),
);
请注意 key 的 controller/method
,如果您没有在调用 form_validation 函数中专门设置它,Codeigniter 将使用它。
一个这样的例子
class Shop extends CI_Controller
{
public function __construct(){ parent::__construct(); }
public function index()
{
// Show the Purchase Form
// in some view
return $this->load->view();
}
public function purchase()
{
// notice we don't pass any params to the run() function
// codeigniter will look inside application/config/form_validation/$config
// for any matching key, ie: shop/purchase
if(!$this->form_validation->run()){
// If validation fails, show the form again
// and stop the method from executing any further
return $this->index();
}
}
}
为了验证是否设置了复选框,我们寻找关键字on
class MY_Form_validation extends CI_Form_validation
{
public function __construct($config)
{
parent::__construct( $config );
}
public function acceptTerms( $field )
{
$this->set_error('acceptTerms', 'your error message');
return (bool) $field == 'on';
}
}
关于php - 如何使 CodeIgniter 可调用留空的复选框,自定义表单验证错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32457463/
我是一名优秀的程序员,十分优秀!