表單驗證是 Web 應用的核心功能之一。CodeIgniter 內建的 Validation 類庫提供了規則設定、錯誤訊息客製化、欄位標籤對應等完整功能。本文以完整專案結構示範,從視圖設計到控制器邏輯,帶你掌握 CI 表單驗證的標準流程。
application/
├── views/
│ ├── myform.php # 表單視圖
│ └── formsuccess.php # 成功視圖
└── controllers/
└── form.php # 表單控制器
myform.php<html>
<head>
<title>My Form</title>
</head>
<body>
<?php echo $this->validation->error_string; ?>
<?php echo form_open('form/index'); ?>
<h5>Username</h5>
<input type="text" name="username" value="" size="50" />
<h5>Password</h5>
<input type="text" name="password" value="" size="50" />
<h5>Password Confirm</h5>
<input type="text" name="passconf" value="" size="50" />
<h5>Email Address</h5>
<input type="text" name="email" value="" size="50" />
<div><input type="submit" value="Submit" /></div>
</form>
</body>
</html>
form_open():自動產生含 CSRF 保護的表單標籤,action 指向 form/index$this->validation->error_string:顯示所有驗證錯誤訊息name 屬性需與驗證規則鍵名一致formsuccess.php<html>
<head><title>My Form</title></head>
<body>
<h3>Your form was successfully submitted!</h3>
<p><?=anchor('form', 'Try it again!'); ?></p>
</body>
</html>
form.php<?php
class Form extends Controller {
function index() {
// 載入輔助函式與驗證類庫
$this->load->helper(array('form', 'url'));
$this->load->library('validation');
// 1. 定義驗證規則
$rules['username'] = "required";
$rules['password'] = "required";
$rules['passconf'] = "required";
$rules['email'] = "required";
$this->validation->set_rules($rules);
// 2. 設定錯誤訊息分隔符(可選)
// $this->validation->set_error_delimiters('', '');
// 3. 定義欄位顯示名稱(用於錯誤訊息)
$fields['username'] = 'Username';
$fields['password'] = 'Password';
$fields['passconf'] = 'Password Confirmation';
$fields['email'] = 'Email Address';
$this->validation->set_fields($fields);
// 4. 執行驗證
if ($this->validation->run() == FALSE) {
$this->load->view('myform');
} else {
$this->load->view('formsuccess');
}
}
}
?>
form 提供 form_open(),url 提供 anchor()name,值為規則字串(支援管線符串聯多規則)run() 回傳布林值,失敗重載表單視圖(保留用戶輸入),成功載入成功視圖| 規則 | 說明 | 範例 |
|---|---|---|
| required | 必填 | "required" |
| min_length[n] | 最小長度 | "min_length[6]" |
| max_length[n] | 最大長度 | "max_length[12]" |
| exact_length[n] | 固定長度 | "exact_length[10]" |
| valid_email | Email 格式 | "valid_email" |
| valid_ip | IP 格式 | "valid_ip" |
| alpha | 僅字母 | "alpha" |
| alpha_numeric | 字母數字 | "alpha_numeric" |
| matches[field] | 與某欄位相同 | "matches[password]" |
| callback_func | 自訂回調函式 | "callback_check_unique" |