029.CI4框架CodeIgniter, 使用POST提交数据时,加载并调用表单验证类validation进行简单数据验证

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)哦,谢谢。

 

猜你喜欢

转载自www.cnblogs.com/tianpan2019/p/12392455.html