01.我們在View目錄中,創建一個登陸的php網頁,代碼如下:
<!doctype html> <html> <head> <title>10年CI一場夢</title> </head> <body> <form action="<?php echo $POST_URL; ?>" method="post" enctype="multipart/form-data"> <p>賬號: <input type="text" name="username"/></p> <p>密碼: <input type="text" name="password"/></p> <input type="submit" name="submit" value="確定"/> </form> </body> </html>
02.我們在控制器中添加表單驗證類,代碼如下:
<?php namespace App\Controllers; // http://127.0.0.1/CI4/public/index.php/hello/ class Hello extends BaseController { public function __construct() { $this->validation = \Config\Services::validation(); //加載表單驗證類庫 helper(['form', 'url']); } public function index() { //判斷是否有提交內容過來 if (!empty($this->request->getPost("submit"))) { $this->validation->setRules([ 'username' => [ 'label' => '賬號', 'rules' => 'required', 'errors' => [ 'required' => '{field} 不能為空!' ] ], 'password' => [ 'label' => '密碼', 'rules' => 'required|min_length[10]', 'errors' => [ 'min_length' => '你的 {field} 太短了!' ] ] ] ); if ($this->validation->withRequest($this->request)->run()) { echo '按鈕: ' . $this->request->getPost("submit") . '<br>'; echo '賬號: ' . $this->request->getPost("username") . '<br>'; echo '密碼: ' . $this->request->getPost("password") . '<br>'; } else { $errors = $this->validation->getErrors(); ShowMessage($errors); } } //顯示View頁面 $data = array('POST_URL' => base_url('public/index.php/hello/'),); echo view('login/login', $data); } }
03.我們用瀏覽器訪問http://localhost/CI4/public/index.php/hello,2個表單輸入的內容如果不滿足表單驗證內容,那么現實的效果如下:
原創不易,如果您認為這篇文章有價值,認同作者的付出,可以微信二維碼打賞任意金額給作者(微信號:382477247)哦,謝謝。