我正在使用codeigniter,如果我的表中存在name
,我想为name
字段创建验证。我得到了空白屏幕,每个人都可以帮助我吗?
这是我的控制者:
public function insertCabang(){
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'nama_cabang', 'trim|required|callback_isNameExist');
}
public function isNameExist($name) {
$this->load->library('form_validation');
$is_exist = $this->cabang_model->isNameExist($name);
if ($is_exist) {
$this->form_validation->set_message('isNameExist', 'Name is already exist.');
return false;
} else {
return true;
}
}
这是我的模特
public function isNameExist($name) {
$this->db->select('nama_cabang');
$this->db->where('nama_cabang', $name);
$query = $this->db->get('master_cabang');
if ($query->num_rows() > 0) {
return true;
} else {
return false;
}
}
提交后我得到了空白屏幕。
谢谢, 马丁
答案 0 :(得分:1)
您只需使用is_unique
执行此操作,而不是使用回调。
您的语法将是
$this->form_validation->set_rules('name', 'nama_cabang', 'trim|required|is_unique[master_cabang.nama_cabang]');
答案 1 :(得分:1)
问题在于您的insertCabang()
控制器功能。你跑了
验证,但它应该怎么做?您必须回显结果,或加载一些视图。
public function insertCabang(){
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'nama_cabang', 'trim|required|callback_isNameExist');
if($this->form_validation->run()){
echo 'validated ok';
}else{echo validation_errors();}
}