我正在开发CI支持的Grocery CRUD应用程序,但在验证时不识别,我需要的是验证字段仅接受字母字符,加号,逗号和空格,但不工作:
控制器功能
Grocery CRUD函数中的代码行数,我称之为solo_letras函数:
Grocery CRUD方法中的代码行数
验证可以取什么值?
使用CodeIgniter中内置的表单验证。我这样做。在函数的开头设置所有表单输入规则,如下所示:
$this->form_validation->set_rules('inputFirstName', 'First Name', required|min_length[4]|max_length[16]|is_unique[users.username]');
这是一个用户名字段的示例。第一个参数是表单输入name='inputFirstName'
,第二个参数是第一个参数的可读版本,用于错误报告,然后是由管道字符分隔的验证。有一个匹配regex的验证;regex_match[/regex/]
.
放置所有验证,然后使用:
if($this->form_validation->run() == false) {
Do something here if validation fails
return false;
}
测试验证。如果验证通过,则继续执行代码。
下面是一个简单注册函数的完整示例:public function register()
{
$this->output->set_content_type('application_json');
$this->form_validation->set_rules('inputUsername', 'User Name', 'required|min_length[4]|max_length[16]|is_unique[users.username]');
$this->form_validation->set_rules('inputEmail', 'Email', 'required|valid_email|is_unique[users.email]');
$this->form_validation->set_rules('inputFirstname', 'First Name', 'required|max_length[20]');
$this->form_validation->set_rules('inputLastname', 'Last Name', 'required|max_length[20]');
$this->form_validation->set_rules('inputPassword', 'Password', 'required|min_length[6]|max_length[16]|matches[inputPasswordConfirm]');
$this->form_validation->set_rules('inputPasswordConfirm', 'Password Confirmation', 'required');
if($this->form_validation->run() == false) {
$this->output->set_output(json_encode(['result' => 0, 'error' => $this->form_validation->error_array()]));
return false;
}
$username = $this->input->post('inputUsername');
$email = $this->input->post('inputEmail');
$firstName = $this->input->post('inputFirstname');
$lastName = $this->input->post('inputLastname');
$password = $this->input->post('inputPassword');
$passwordConfirm = $this->input->post('inputPasswordConfirm');
$this->load->model('user_model');
$user_id = $this->user_model->insert([
'username' => $username,
'email' => $email,
'firstName' => $firstName,
'lastName' => $lastName,
'password' => hash('sha256', $password . PASSWORD_SALT)
]);
if($user_id) {
$this->session->set_userdata(['user_id' => $user_id]);
$this->output->set_output(json_encode(['result' => 1]));
return false;
}
$this->output->set_output(json_encode(['result' => 0, 'error' => "User not created."]));
}