pig*_*fox 5 php validation codeigniter
我有一个名为"business_id"的下拉列表.
<select name="business_id">
<option value="0">Select Business</option> More options...
</select>
Run Code Online (Sandbox Code Playgroud)
验证规则就是这里,用户必须选择一个选项.
$this->form_validation->set_rules('business_id', 'Business', 'greater_than[0]');
Run Code Online (Sandbox Code Playgroud)
问题是错误消息说:业务字段必须包含大于0的数字.不是很直观!我想要它说"你必须选择一个企业".
我试过了:
$this->form_validation->set_message('Business', 'You must select a business');
Run Code Online (Sandbox Code Playgroud)
但CI完全忽略了这一点.有人有解决方案吗?
我在codeigniter 2中添加自定义表单验证错误消息的要求相同(例如"您必须同意我们的条款和条件").当然,覆盖require和greater_than的错误消息是错误的,因为它会错误地为表单的其余部分生成消息.我扩展了CI_Form_validation类并重写了set_rules方法以接受新的'message'参数:
<?php
class MY_Form_validation extends CI_Form_validation
{
private $_custom_field_errors = array();
public function _execute($row, $rules, $postdata = NULL, $cycles = 0)
{
// Execute the parent method from CI_Form_validation.
parent::_execute($row, $rules, $postdata, $cycles);
// Override any error messages for the current field.
if (isset($this->_error_array[$row['field']])
&& isset($this->_custom_field_errors[$row['field']]))
{
$message = str_replace(
'%s',
!empty($row['label']) ? $row['label'] : $row['field'],
$this->_custom_field_errors[$row['field']]);
$this->_error_array[$row['field']] = $message;
$this->_field_data[$row['field']]['error'] = $message;
}
}
public function set_rules($field, $label = '', $rules = '', $message = '')
{
$rules = parent::set_rules($field, $label, $rules);
if (!empty($message))
{
$this->_custom_field_errors[$field] = $message;
}
return $rules;
}
}
?>
Run Code Online (Sandbox Code Playgroud)
使用上面的类,您将生成带有自定义错误消息的规则,如下所示:
$this->form_validation->set_rules('business_id', 'Business', 'greater_than[0]', 'You must select a business');
Run Code Online (Sandbox Code Playgroud)
您也可以在自定义消息中使用'%s',它将自动填写fieldname的标签.
小智 6
如果您想自定义每个规则显示的错误消息,您可以在以下位置的数组中找到它们:
/system/language/english/form_validation_lang.php
Run Code Online (Sandbox Code Playgroud)
尝试不要在默认选择上设置 value 属性...
<select name="business_id">
<option value>Select Business</option> More options...
</select>
Run Code Online (Sandbox Code Playgroud)
然后只需使用表单验证规则所需的...
$this->form_validation->set_rules('business_id', 'Business', 'required');
Run Code Online (Sandbox Code Playgroud)
我想您也可以尝试编辑您尝试设置消息的方式......
$this->form_validation->set_message('business_id', 'You must select a business');
instead of
$this->form_validation->set_message('Business', 'You must select a business');
Run Code Online (Sandbox Code Playgroud)
但我并不完全确定这是否能起到作用。