CodeIgniter 4中的自定义验证规则教程

210 阅读1分钟

下载并安装CodeIgniter 4

下载最新版本的CodeIgniter 4,并将源代码解压到名为LearnCodeIgniter4WithRealApps的新文件夹。

公共文件夹中的index.phphtaccess文件剪切到项目的文件夹中。

打开文件夹中的index.php,找到第16行,将路径替换为Paths.php文件,如下所示。

$pathsPath = realpath(FCPATH . '/app/Config/Paths.php');

打开app/Config文件夹中的App.php,找到第39行,在$indexPage变量中删除index.php字符串,如下所示。

public $indexPage = '';

设置BASE URL

打开app/Config文件夹中的App.php文件。设置**$baseURL**变量的值,如下所示。

public $baseURL = 'http://localhost:8091/LearnCodeIgniter4WithRealApps/';

创建控制器

app/Controllers文件夹下创建名为Account.php的新PHP文件,如下所示。

<?php

namespace App\Controllers;

class Account extends BaseController
{
	public function __construct()
	{
		helper(['url', 'form']);
	}

	public function index()
	{
		return view('account/index', [
			'validation' => \Config\Services::validation()
		]);
	}

	public function save()
	{
		$isValid = $this->validate([
			'username' => 'trim|required|min_length[3]|max_length[12]',
			'password' => 'trim|required|min_length[6]|max_length[20]|regex_match[/^((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})$/]',
			'repassword' => 'trim|required|min_length[3]|max_length[20]|matches[password]',
			'age' => 'trim|required|integer|greater_than[18]|less_than[120]',
			'email' => 'trim|required|valid_email',
			'website' => 'trim|valid_url',
		]);
		if (!$isValid) {
			return view('account/index', [
				'validation' => \Config\Services::validation()
			]);
		} else {
			$request = \Config\Services::request();
            $data['account'] = $request->getPost();
            return view('account/success', $data);
		}
	}
}											

创建视图

app/Views文件夹下创建名为account的新文件夹。在这个文件夹中,创建新的PHP文件,命名如下。

索引视图

account文件夹中,创建名为index.php的新的PHP文件,如下所示。

<html>

	<head>
		<title>Codeigniter 4 Form Validation</title>
	</head>

	<body>

		<h3>Register</h3>
		<ul>
			<?php foreach ($validation->getErrors() as $error) : ?>
				<li><?= $error ?></li>
			<?php endforeach ?>
		</ul>
		<form method="post" action="<?= site_url('account/save') ?>">
			<table cellpadding="2" cellspacing="2">
				<tr>
					<td>Username</td>
					<td>
						<input type="text" name="username" value="<?= set_value('username'); ?>" />
					</td>
					<td><?= $validation->getError('username') ?></td>
				</tr>
				<tr>
					<td>Password</td>
					<td>
						<input type="password" name="password" />
					</td>
					<td><?= $validation->getError('password') ?></td>
				</tr>
				<tr>
					<td>Re-Password</td>
					<td>
						<input type="password" name="repassword" />
					</td>
					<td><?= $validation->getError('repassword') ?></td>
				</tr>
				<tr>
					<td>Age</td>
					<td>
						<input type="text" name="age" />
					</td>
					<td><?= $validation->getError('age') ?></td>
				</tr>
				<tr>
					<td>Email</td>
					<td>
						<input type="text" name="email" />
					</td>
					<td><?= $validation->getError('email') ?></td>
				</tr>
				<tr>
					<td>Website</td>
					<td>
						<input type="text" name="website" />
					</td>
					<td><?= $validation->getError('website') ?></td>
				</tr>
				<tr>
					<td>&nbsp;</td>
					<td>
						<input type="submit" value="Save" />
					</td>
				</tr>
			</table>
		</form>

	</body>

</html>

成功视图

account文件夹中,创建名为success.php的新的PHP文件,如下所示。

<html>

	<head>
		<title>Codeigniter 4 Form Validation</title>
	</head>

	<body>

		<h3>Account Info</h3>
		<table cellpadding="2" cellspacing="2" border="1">
			<tr>
				<td>Username</td>
				<td><?= $account['username'] ?></td>
			</tr>
			<tr>
				<td>Password</td>
				<td><?= $account['password'] ?></td>
			</tr>
			<tr>
				<td>Age</td>
				<td><?= $account['age'] ?></td>
			</tr>
			<tr>
				<td>Email</td>
				<td><?= $account['email'] ?></td>
			</tr>
			<tr>
				<td>Website</td>
				<td><?= $account['website'] ?></td>
			</tr>
		</table>

	</body>

</html>
			

定义路线

打开app/Config文件夹中的Routes.php文件,定义路线如下。

$routes->get('/', 'Account::index');
$routes->post('/account/save', 'Account::save');

CodeIgniter项目的结构

运行应用程序

使用以下网址访问账户控制器中的index动作:http://localhost:8091/LearnCodeIgniterWithRealApps/account/index

输出

点击保存按钮提交表单,在账户控制器中保存无效数据的动作,如下所示。

(adsbygoogle = window.adsbygoogle || []).push({})。

点击 "保存"按钮提交表单,在账户控制器中保存有效数据的操作。

输出