升级验证
库文档
变更点
如果要更改验证错误显示,必须设置 CI4 验证视图模板。
CI4 验证格式规则不允许为空字符串。
CI4 验证永远不会改变你的数据。
从 v4.3.0 开始,引入了
validation_errors()
,但 API 与 CI3 的不同。
升级指南
在包含表单的视图中进行更改:
<?php echo validation_errors(); ?>
改为<?= validation_list_errors() ?>
在控制器中进行更改:
$this->load->helper(array('form', 'url'));
改为helper(['form', 'url']);
移除
$this->load->library('form_validation');
if ($this->form_validation->run() == FALSE)
改为if (! $this->validate([]))
$this->load->view('myform');
改为return view('myform', ['validation' => $this->validator,]);
必须更改验证规则。新语法是在控制器中将规则设置为数组:
<?php $isValid = $this->validate([ 'name' => 'required|min_length[3]', 'email' => 'required|valid_email', 'phone' => 'required|numeric|max_length[10]', ]);
代码示例
CodeIgniter 3.x 版本
路径:application/views:
<html>
<head>
<title>My Form</title>
</head>
<body>
<?php echo validation_errors(); ?>
<?php echo form_open('form'); ?>
<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>
路径:application/controllers:
<?php
class Form extends CI_Controller {
public function index()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
// Set validation rules
if ($this->form_validation->run() == FALSE) {
$this->load->view('myform');
} else {
$this->load->view('formsuccess');
}
}
}
CodeIgniter 4.x 版本
路径:app/Views:
<html>
<head>
<title>My Form</title>
</head>
<body>
<?= validation_list_errors() ?>
<?= form_open('form') ?>
<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>
路径:app/Controllers:
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
class Form extends Controller
{
public function index()
{
helper(['form', 'url']);
if (! $this->validate([
// Validation rules
])) {
return view('myform');
}
return view('formsuccess');
}
}