我为每个验证规则的每个输入字段都包含自定义错误消息。 规则如下。
$config = array(
'firstname' => array(
'trim' => array(
'label' => 'First Name',
'rule' => 'trim'
),
'xss_clean' => array(
'label' => 'First Name',
'rule' => 'xss_clean'
),
'required' => array(
'label' => 'First Name',
'rule' => 'required',
'message' => 'This field is required.'
)
),
'lastname' => array(
'trim' => array(
'label' => 'Last Name',
'rule' => 'trim'
),
'xss_clean' => array(
'label' => 'Last Name',
'rule' => 'xss_clean'
),
'required' => array(
'label' => 'Last Name',
'rule' => 'required',
'message' => 'This field is required.'
)
),
'email' => array(
'valid_email' => array(
'label' => 'Email',
'rule' => 'valid_email',
'message' => 'This field should be email.'
),
'required' => array(
'label' => 'Email',
'rule' => 'required',
'message' => 'This field is required.'
)
),
'password' => array(
'match' => array(
'label' => 'Confirm Password',
'rule' => 'matches[confirm_password]',
'message' => 'These passwords don\'t match. Try again?.'
),
'length' => array(
'label' => 'Password',
'rule' => 'min_length[6]',
'message' => 'This field should\'ve atleast 6 characters.'
),
'required' => array(
'label' => 'Password',
'rule' => 'required',
'message' => 'This field is required.'
)
),
'confirm_password' => array(
'required' => array(
'label' => 'Confirm Password',
'rule' => 'required',
'message' => 'This field is required.'
)
));
foreach($config as $key => $fields) {
foreach($fields as $rule => $field) {
if(isset($field['message']) && !empty($field['message'])) {
$field['rule'] = preg_replace('/\[.*\]/', '', $field['rule']);
$this->form_validation->set_message($field['rule'], $field['message']);
}
$this->form_validation->set_rules($key, $field['label'], $field['rule']);
}
}
if ($this->form_validation->run()) {
return true;
}
return false;
但是valid_email
,'min_length'和matches
规则无效。请帮我找出解决方案。字面上浪费时间。这项工作会更加丰富。
答案 0 :(得分:0)
关于min_length
和matches
,您应删除或评论该行
$field['rule'] = preg_replace('/\[.*\]/', '', $field['rule']);
删除大括号[]
,其中包含角色运行所需的内部条件
关于valid_email
没有错,可能需要检查视图/表单中的字段名称。
或者您可以简单地使用传统方法:
$this -> form_validation -> set_rules('firstname', 'First Name', 'trim|xss_clean|required');
$this -> form_validation -> set_rules('lastname', 'Last Name', 'trim|xss_clean|required');
$this -> form_validation -> set_rules('email', 'Email', 'required|valid_email');
$this -> form_validation -> set_rules('password', 'Password', 'required|min_length[6]|matches[confirm_password]');
$this -> form_validation -> set_rules('confirm_password', 'Confirm Password', 'required');
$this -> form_validation -> set_message('required', ' %s Required');
$this -> form_validation -> set_message('valid_email', 'Invalid %s');
$this -> form_validation -> set_message('min_length', '%s should\'ve at least 6 characters.');
$this -> form_validation -> set_message('matches', 'These passwords don\'t match. Try again?.');
if ($this -> form_validation -> run()) {
return true;
}
return false;