我有一个自定义规则regex[table_name.column_name.post_value]
,我以以下方式使用它:
$this->form_validation->set_rules(
'postal_code',
'Postal code',
'regex[countries.postal_code_regex.country_code]'
);
下面是我的自定义规则在MY_Form_validation.php:
中的函数public function regex($str, $field){
list($table, $col, $post_val)=explode('.', $field);
// Grab the regex
$regex = $this->CI ->db
->limit(1)
->select($col)
->where($post_val, $_POST[$post_val])
->get($table)
->row($col);
return preg_match('/'.$regex.'/', $str) === 1;
}
如果用户发送一个空字符串,我如何让CodeIgniter运行此规则?
注意:我不能使用required
规则,因为它取决于数据库是否有正则表达式。
尝试下面的代码:
public function regex($str, $field){
list($table, $col, $post_val)=explode('.', $field);
// Grab the regex
$regex = $this->CI ->db
->limit(1)
->select($col)
->where($post_val, $_POST[$post_val])
->get($table)
->row($col);
if(trim($str) === "")
$str = 1;
return preg_match('/'.$regex.'/', $str) === 1;
}
对于我自己的问题,我想出了这个相当难看的解决方案:
if( isset($_POST['country_code']) && $_POST['postal_code'] == NULL){
$_POST['postal_code'] = ' ';
}
然后我添加了trim
规则,以确保它不会在数据库中存储空间。
当然,如果有人能想出更好的解决办法,我洗耳恭听。