2016-09-22 45 views

回答

0

在CodeIgniter中使用內置的表單驗證。 我這樣做。 在你的函數的開始設置你這樣的形式輸入的所有規則:

$this->form_validation->set_rules('inputFirstName', 'First Name', required|min_length[4]|max_length[16]|is_unique[users.username]'); 

這是一個用戶名字段的樣本。第一個參數是表單輸入name='inputFirstName',第二個參數是第一個參數的可讀版本,用於錯誤報告,然後是由管道字符分隔的驗證。有一個匹配正則表達式的驗證; 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."])); 

    } 
+0

我理解,但我需要的是驗證了現場只接受來自一個字符到Z除了下列字符{[空格] 。 ,} –

+0

這是一個很棒的正則表達式測試網站。 http://www.regexr.com/ – Dominofoe

+0

對不起,另一個包括數字。這是你想要的。 '/ [A-Z,A-Z \ S \。\,]/g' – Dominofoe