驗(yàn)證類?

CodeIgniter 提供了全面的數(shù)據(jù)驗(yàn)證類,最大程度減少你需要編寫的代碼量。

概述?

在解釋 CodeIgniter 的數(shù)據(jù)驗(yàn)證之前,我們先介紹理想的狀況:

  1. 顯示一個(gè)表單。
  2. 你填寫并提交。
  3. 如果你提交的表單數(shù)據(jù)無效,或者丟失了必填項(xiàng),將重新顯示包含了你的數(shù)據(jù)和錯(cuò)誤消息的表單。
  4. 這個(gè)過長將一直持續(xù)到你提交的表單數(shù)據(jù)有效為止。

在接收端,腳本必須:

  1. 檢查需要的數(shù)據(jù)。
  2. 驗(yàn)證數(shù)據(jù)的類型是否正確,并且符合要求的標(biāo)準(zhǔn)。例如,如果提交了用戶名,則必須僅包含允許的字符。 它必須大于最小長度,小于最大長度。用戶名不能是系統(tǒng)中已經(jīng)存在的用戶名,甚至是保留的關(guān)鍵詞。 等等。
  3. 處理數(shù)據(jù)以保證安全。
  4. 如果有必要,對(duì)數(shù)據(jù)進(jìn)行格式化 (是否需要裁剪數(shù)據(jù) ? HTML 編碼? 等等。)
  5. 準(zhǔn)備要插入數(shù)據(jù)庫的數(shù)據(jù)。

盡管上述過程沒有什么非常復(fù)雜的,但是通常需要編寫大量的代碼,并且顯示各種錯(cuò)誤消息,在 HTML 表單中 放置各種控制結(jié)構(gòu)。表單驗(yàn)證雖然容易創(chuàng)建,但是通常十分混亂,實(shí)現(xiàn)起來很繁瑣。

表單驗(yàn)證教程?

以下是實(shí)現(xiàn) CodeIgniter 表單驗(yàn)證的“動(dòng)手”教程。

為了實(shí)現(xiàn)表單驗(yàn)證,你需要做三件事:

  1. 一個(gè)包含表單的 View 文件。
  2. 一個(gè)提交成功后顯示 “success” 的 View 文件。
  3. 一個(gè) controller 方法用來接收和處理提交的數(shù)據(jù)。

讓我們以會(huì)員注冊表單為例來做這三件事。

表單?

使用編輯器創(chuàng)建一個(gè)名為 Signup.php 的視圖文件,將代碼復(fù)制到文件中,并保存到 app/Views/ 文件夾:

<html>
<head>
    <title>My Form</title>
</head>
<body>

    <?= $validation->listErrors() ?>

    <?= 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>

成功頁?

使用編輯器創(chuàng)建一個(gè)名為 Success.php 的視圖文件,將代碼復(fù)制到文件中,并保存到 app/Views/ 文件夾:

<html>
<head>
    <title>My Form</title>
</head>
<body>

    <h3>Your form was successfully submitted!</h3>

    <p><?= anchor('form', 'Try it again!') ?></p>

</body>
</html>

控制器?

使用編輯器創(chuàng)建一個(gè)名為 Form.php 的控制器文件,將代碼復(fù)制到文件中,并保存到 app/Controllers/ 文件夾:

<?php namespace App\Controllers;

use CodeIgniter\Controller;

class Form extends Controller
{
    public function index()
    {
        helper(['form', 'url']);

        if (! $this->validate([]))
        {
            echo view('Signup', [
                'validation' => $this->validator
            ]);
        }
        else
        {
            echo view('Success');
        }
    }
}

試一試!?

要嘗試使用表單,請使用與此網(wǎng)址相似的網(wǎng)址訪問你的網(wǎng)站

example.com/index.php/form/

如果你提交表單,則應(yīng)該只看到表單重新加載。那是因?yàn)槟銢]有設(shè)置任何驗(yàn)證規(guī)則。

注解

由于你沒有告訴 Validation 類 進(jìn)行任何驗(yàn)證, 它在 默認(rèn)情況返回 false (boolean false)。 validate() 方法僅在驗(yàn)證你設(shè)置的 所有規(guī)則 并且沒有 任何失敗 的情況下返回 true 。

說明?

你會(huì)注意到上述頁面的幾件事情:

表單 (Signup.php) 是一個(gè)標(biāo)準(zhǔn)的 web 表單,但有一些例外:

  1. 它使用表單輔助類來創(chuàng)建表單。從技術(shù)上講這沒必要,你可以使用標(biāo)準(zhǔn)的 HTML 代碼來創(chuàng)建表單。 但是,使用表單輔助類可以根據(jù)配置文件中的 URL 來生成表單的 action URL。當(dāng)你的網(wǎng)址發(fā)生 更改時(shí),則你的程序更容易進(jìn)行移植。

  2. 在表單的頂部,你會(huì)注意到調(diào)用了以下函數(shù):

    <?= $validation->listErrors() ?>
    

    該函數(shù)將返回 validator 發(fā)送的所有錯(cuò)誤消息。如果沒有消息,則返回一個(gè)空字符串。

控制器 (Form.php) 擁有一個(gè)方法: index()。這個(gè)方法使用控制器提供的 validate 方法, 并加載表單輔助類和 URL 輔助類。它還運(yùn)行驗(yàn)證程序,根據(jù)驗(yàn)證程序是否驗(yàn)證成功,它將顯示表單或成功頁。

加載 validation 庫?

該庫通過名叫 validation 的服務(wù)進(jìn)行加載:

$validation =  \Config\Services::validation();

這將自動(dòng)加載 Config\Validation 文件,文件中包含了多個(gè)規(guī)則類,以及便于重用的規(guī)則集合。

注解

你可用永遠(yuǎn)都不會(huì)使用該方法,因?yàn)?ControllerModel 中都提供了更簡便的驗(yàn)證方法。

設(shè)置驗(yàn)證規(guī)則?

CodeIgniter 允許你為給定字段設(shè)置多個(gè)驗(yàn)證規(guī)則,并按順序執(zhí)行它們。要設(shè)置驗(yàn)證規(guī)則,你將使用 setRule(),setRules() 方法。

setRule()?

該方法設(shè)置單個(gè)規(guī)則,它使用 字段名稱 作為第一個(gè)參數(shù),第二個(gè)參數(shù)是一個(gè)可選的標(biāo)簽,第三個(gè)參數(shù)是以豎線 分隔的規(guī)則列表的字符串:

$validation->setRule('username', 'Username', 'required');

字段名稱 必須與需要驗(yàn)證的任何數(shù)據(jù)數(shù)組的鍵匹配。如果直接從 $_POST 獲取數(shù)組,則它必須與表單的 input name 完全匹配。

setRules()?

setRule() 類似,但其接受字段名稱與其規(guī)則所組成的數(shù)組:

$validation->setRules([
    'username' => 'required',
    'password' => 'required|min_length[10]'
]);

想設(shè)置帶標(biāo)簽的錯(cuò)誤消息,你可以像這樣設(shè)置:

$validation->setRules([
    'username' => ['label' => 'Username', 'rules' => 'required'],
    'password' => ['label' => 'Password', 'rules' => 'required|min_length[10]']
]);

withRequest()?

使用驗(yàn)證庫最常見的場景之一是驗(yàn)證從 HTTP 請求輸入的數(shù)據(jù)。如果需要,你可以傳遞當(dāng)前的 Request 對(duì)象的實(shí)例, 它將接收所有輸入數(shù)據(jù),并將其設(shè)置為待驗(yàn)證的數(shù)據(jù):

$validation->withRequest($this->request)
           ->run();

處理 Validation?

驗(yàn)證數(shù)組的鍵?

如果需要驗(yàn)證的數(shù)據(jù)在嵌套的關(guān)聯(lián)數(shù)組中,則可以使用 “點(diǎn)數(shù)組語法” 輕松驗(yàn)證數(shù)據(jù):

// The data to test:
'contacts' => [
    'name' => 'Joe Smith',
    'friends' => [
        [
            'name' => 'Fred Flinstone'
        ],
        [
            'name' => 'Wilma'
        ]
    ]
]

// Joe Smith
$validation->setRules([
    'contacts.name' => 'required'
]);

// Fred Flintsone & Wilma
$validation->setRules([
    'contacts.friends.name' => 'required'
]);

你可以使用通配符 “*” 來匹配數(shù)組的任何一個(gè)層級(jí):

// Fred Flintsone & Wilma
$validation->setRules([
    'contacts.*.name' => 'required'
]);

“點(diǎn)數(shù)組語法” 也通常用于一維數(shù)組。例如,多選下拉列表返回的數(shù)據(jù):

// The data to test:
'user_ids' => [
    1,
    2,
    3
]
// Rule
$validation->setRules([
    'user_ids.*' => 'required'
]);

驗(yàn)證單個(gè)值?

根據(jù)規(guī)則驗(yàn)證單個(gè)值:

$validation->check($value, 'required');

將驗(yàn)證規(guī)則集合保存到配置文件?

Validation 類一個(gè)好的功能是,它允許你將整個(gè)程序的驗(yàn)證規(guī)則存儲(chǔ)在配置文件中。將規(guī)則組合成一個(gè) “group” ,可以在運(yùn)行驗(yàn)證時(shí)指定不同的組。

如何保存你的規(guī)則?

要存儲(chǔ)你的驗(yàn)證規(guī)則,只需在 Config\Validation 類中使用 group 名創(chuàng)建一個(gè)新的公共屬性, 該元素將包含你的驗(yàn)證規(guī)則數(shù)組。驗(yàn)證規(guī)則數(shù)組的原型如下所示:

class Validation
{
    public $signup = [
        'username'     => 'required',
        'password'     => 'required',
        'pass_confirm' => 'required|matches[password]',
        'email'        => 'required|valid_email'
    ];
}

你可以在調(diào)用 run() 方法時(shí)指定要使用的組:

$validation->run($data, 'signup');

你也可以將自定義錯(cuò)誤消息存儲(chǔ)在配置文件中,屬性名稱與組名相同并添加 _errors。 當(dāng)使用該組時(shí),默認(rèn)的錯(cuò)誤消息將被替換:

class Validation
{
    public $signup = [
        'username'     => 'required',
        'password'     => 'required',
        'pass_confirm' => 'required|matches[password]',
        'email'        => 'required|valid_email'
    ];

    public $signup_errors = [
        'username' => [
            'required'    => 'You must choose a username.',
        ],
        'email'    => [
            'valid_email' => 'Please check the Email field. It does not appear to be valid.'
        ]
    ];
}

或者在組中傳遞所有的設(shè)置:

class Validation
{
    public $signup = [
        'username' => [
            'rules'  => 'required',
            'errors' => [
                'required' => 'You must choose a Username.'
            ]
        ],
        'email'    => [
            'rules'  => 'required|valid_email',
            'errors' => [
                'valid_email' => 'Please check the Email field. It does not appear to be valid.'
            ]
        ],
    ];
}

有關(guān)數(shù)組格式的詳細(xì)信息請查看下文。

獲取與設(shè)置規(guī)則組?

獲取規(guī)則組

該方法從驗(yàn)證配置中獲取規(guī)則組:

$validation->getRuleGroup('signup');

設(shè)置規(guī)則組

該方法設(shè)置將規(guī)則組從驗(yàn)證配置設(shè)置到驗(yàn)證服務(wù):

$validation->setRuleGroup('signup');

運(yùn)行多個(gè) Validation?

注解

run() 方法不會(huì)重置錯(cuò)誤狀態(tài)。如果上次運(yùn)行失敗,run() 方法將始終返回 false , getErrors() 方法將始終返回上次的所有錯(cuò)誤,直至狀態(tài)被顯式重置。

如果需要運(yùn)行多個(gè)驗(yàn)證,例如在不同的數(shù)據(jù)集上運(yùn)行或者一個(gè)接一個(gè)的運(yùn)行不同的規(guī)則,你應(yīng)該在每次運(yùn)行前 調(diào)用 $validation->reset() 清除上次運(yùn)行產(chǎn)生的錯(cuò)誤。需要注意的是 reset() 將重置之前的所有數(shù)據(jù)、規(guī)則 或是自定義錯(cuò)誤消息。所以需要重復(fù) setRules(),setRuleGroup() 等方法:

for ($userAccounts as $user) {
    $validation->reset();
    $validation->setRules($userAccountRules);
    if (!$validation->run($user)) {
        // handle validation errors
    }
}

Validation 占位符?

Validation 類提供了一個(gè)簡單的方法,可以根據(jù)傳入的數(shù)據(jù)替換部分規(guī)則。這聽起來十分晦澀,但在使用 is_unique 進(jìn)行驗(yàn)證時(shí) 十分方便。 占位符是字段的名稱(或數(shù)組的鍵),該字段名稱(或數(shù)組的鍵)將用花括號(hào)包起來作為 $data 傳入。它將被替換為匹配的 傳入字段的 。 以下例子可以解釋這些:

$validation->setRules([
    'email' => 'required|valid_email|is_unique[users.email,id,{id}]'
]);

在這組規(guī)則中,它聲明 email 在數(shù)據(jù)庫中是唯一的,除了具有與占位符匹配的 id 信息, 假設(shè)表單 POST 數(shù)據(jù)中有以下內(nèi)容:

$_POST = [
    'id' => 4,
    'email' => 'foo@example.com'
];

那么占位符 {id} 將被修改為數(shù)字 4,以下是修改后的規(guī)則:

$validation->setRules([
    'email' => 'required|valid_email|is_unique[users.email,id,4]'
]);

因此,在驗(yàn)證 email 唯一時(shí),將忽略數(shù)據(jù)庫中 id=4 的行。

這也可以用于在運(yùn)行時(shí)動(dòng)態(tài)創(chuàng)建更多的規(guī)則,只要你確保傳入的任何動(dòng)態(tài)鍵都不會(huì)與表單 數(shù)據(jù)產(chǎn)生沖突。

處理錯(cuò)誤?

Validation 庫提供了幾種方法幫助你設(shè)置錯(cuò)誤消息,提供自定義錯(cuò)誤消息,以及顯示一個(gè) 或多個(gè)錯(cuò)誤消息。

默認(rèn)情況下,錯(cuò)誤消息來自 system/Language/en/Validation.php 中的語言字符串, 其中每個(gè)規(guī)則都有一個(gè)條目。

設(shè)置自定義錯(cuò)誤消息?

setRule()setRules() 允許自定義錯(cuò)誤消息數(shù)據(jù)作為最后一個(gè)參數(shù)傳入。每一個(gè)錯(cuò)誤的 錯(cuò)誤消息都是定制的,這將帶來愉快的用戶體驗(yàn)。如果沒有設(shè)置自定義錯(cuò)誤消息,則提供默認(rèn)值。

這是兩種設(shè)置錯(cuò)誤消息的方式。

作為最后一個(gè)參數(shù):

$validation->setRules([
        'username' => 'required|is_unique[users.username]',
        'password' => 'required|min_length[10]'
    ],
    [   // Errors
        'username' => [
            'required' => 'All accounts must have usernames provided',
        ],
        'password' => [
            'min_length' => 'Your password is too short. You want to get hacked?'
        ]
    ]
);

或者作為標(biāo)簽樣式:

$validation->setRules([
        'username' => [
            'label'  => 'Username',
            'rules'  => 'required|is_unique[users.username]',
            'errors' => [
                'required' => 'All accounts must have {field} provided'
            ]
        ],
        'password' => [
            'label'  => 'Password',
            'rules'  => 'required|min_length[10]',
            'errors' => [
                'min_length' => 'Your {field} is too short. You want to get hacked?'
            ]
        ]
    ]
);

如果你希望包含字段的“human”名稱,或者某些規(guī)則允許的可選參數(shù) (比如 max_length),或當(dāng)前參與驗(yàn)證的值, 則可以分別將 {field}{param},{value} 標(biāo)記添加到你的消息中:

'min_length' => 'Supplied value ({value}) for {field} must have at least {param} characters.'

在一個(gè)用戶名字段為 Username ,驗(yàn)證規(guī)則為 min_length[6] ,字段值為 “Pizza” 的驗(yàn)證中,將顯示錯(cuò)誤消息 “Supplied value (Pizza) for Username must have at least 6 characters”

注解

如果你傳遞最后一個(gè)參數(shù),則標(biāo)簽樣式的錯(cuò)誤信息將被忽略。

消息和驗(yàn)證標(biāo)簽的翻譯?

要使用語言文件中的翻譯字符串,可以簡單的使用點(diǎn)語法。假設(shè)我們有一個(gè)包含翻譯的文件位 于 app/Languages/en/Rules.php。我們可以簡單的使用定義在文件中的語言行,如下:

$validation->setRules([
        'username' => [
            'label'  => 'Rules.username',
            'rules'  => 'required|is_unique[users.username]',
            'errors' => [
                'required' => 'Rules.username.required'
            ]
        ],
        'password' => [
            'label'  => 'Rules.password',
            'rules'  => 'required|min_length[10]',
            'errors' => [
                'min_length' => 'Rules.password.min_length'
            ]
        ]
    ]
);

獲取所有錯(cuò)誤?

如果你需要檢索所有驗(yàn)證失敗字段的錯(cuò)誤消息,你可以使用 getErrors() 方法:

$errors = $validation->getErrors();

// Returns:
[
    'field1' => 'error message',
    'field2' => 'error message',
]

如果沒有錯(cuò)誤,則返回空數(shù)組。

獲取單個(gè)錯(cuò)誤?

你可以使用 getError() 方法檢索單個(gè)字段的錯(cuò)誤消息。參數(shù)名是唯一的參數(shù):

$error = $validation->getError('username');

如果沒有錯(cuò)誤,則返回空字符串。

檢查是否存在錯(cuò)誤?

你可以使用 hasError() 方法檢查字段是否存在錯(cuò)誤。字段名是唯一的參數(shù):

if ($validation->hasError('username'))
{
    echo $validation->getError('username');
}

自定義錯(cuò)誤顯示?

當(dāng)你調(diào)用 $validation->listErrors()$validation->showError() ,它將在后臺(tái)加載一個(gè)視圖文件, 該文件確定錯(cuò)誤的顯示方法。默認(rèn)情況下,它在經(jīng)過包裝的 div 上顯示 errors 。你可以輕松的創(chuàng)建視圖并在整個(gè)程序 中使用它。

創(chuàng)建視圖?

第一步是創(chuàng)建視圖文件,它可以放在 view() 方法可以加載的任何地方。這意味著標(biāo)準(zhǔn)的 View 目錄,或者任何命名空間 下的 View 目錄都可以正常工作。例如,可以在 /app/Views/_errors_list.php 創(chuàng)建新的視圖文件:

<div class="alert alert-danger" role="alert">
    <ul>
    <?php foreach ($errors as $error) : ?>
        <li><?= esc($error) ?></li>
    <?php endforeach ?>
    </ul>
</div>

$errors 數(shù)組可以在包含錯(cuò)誤列表的視圖中使用,其中鍵是發(fā)生錯(cuò)誤的字段名,值是錯(cuò)誤消息,如下所示:

$errors = [
    'username' => 'The username field must be unique.',
    'email'    => 'You must provide a valid email address.'
];

實(shí)際上可以創(chuàng)建兩種類型的視圖文件。第一種包含所有錯(cuò)誤消息,這就是我們剛才看到的。另一種更簡單,只包含一個(gè)錯(cuò)誤消息變量 $error。 它與指定字段名的 showError() 方法一起使用。

<span class="help-block"><?= esc($error) ?></span>

配置?

創(chuàng)建視圖后,需要讓 Validation 庫知道它們。 打開 Config/Validation.php,在里面找到 $templates 屬性。 你可以在其中列出任意多個(gè)自定義視圖,并提供一個(gè)可以引用他們的短別名。我們將添加上邊的示例文件,它看起來像:

public $templates = [
    'list'    => 'CodeIgniter\Validation\Views\list',
    'single'  => 'CodeIgniter\Validation\Views\single',
    'my_list' => '_errors_list'
];

指定模板?

通過將別名作為 listErrors 方法的第一個(gè)參數(shù),來指定要使用的模板:

<?= $validation->listErrors('my_list') ?>

當(dāng)顯示特定字段錯(cuò)誤時(shí),你可以將別名作為第二個(gè)參數(shù)傳遞給 showError 方法,別名參數(shù)應(yīng)該在字段名稱之后:

<?= $validation->showError('username', 'my_single') ?>

創(chuàng)建自定義規(guī)則?

規(guī)則簡單的存儲(chǔ)在命名空間類中。只要自動(dòng)加載器能找到它們,你可將他們存儲(chǔ)到任何位置。這些文件稱作規(guī)則集。要添加新的規(guī)則集, 請編輯 Config/Validation.php 并將新文件添加到 $ruleSets 數(shù)組:

public $ruleSets = [
    \CodeIgniter\Validation\Rules::class,
    \CodeIgniter\Validation\FileRules::class,
    \CodeIgniter\Validation\CreditCardRules::class,
];

你可以將其添加為具有完全限定類的簡單字符串,或者使用 ::class 后綴進(jìn)行添加。如上所示,這里的好處是,它在更高級(jí)的 IED 中提供了額外的一些導(dǎo)航功能。

在文件中,每一個(gè)方法都是一個(gè)規(guī)則,它必須接受字符串作為第一個(gè)字符串,并且必須返回布爾值 true 或 false 。如果通過測試則返回 true ,否則返回 false 。

class MyRules
{
    public function even(string $str): bool
    {
        return (int)$str % 2 == 0;
    }
}

默認(rèn)情況下,系統(tǒng)將在 CodeIgniter\Language\en\Validation.php 中查找錯(cuò)誤要使用語言字符串。在自定義規(guī)則中,你可以通過第二個(gè)參數(shù) $error 的引用來 提供錯(cuò)誤消息:

public function even(string $str, string &$error = null): bool
{
    if ((int)$str % 2 != 0)
    {
        $error = lang('myerrors.evenError');
        return false;
    }

    return true;
}

現(xiàn)在你可像其他規(guī)則一樣使用新的自定義規(guī)則:

$this->validate($request, [
    'foo' => 'required|even'
]);

允許參數(shù)?

如果你的方法需要使用參數(shù),則該函數(shù)至少需要三個(gè)參數(shù):要驗(yàn)證的字符串、參數(shù)字符串以及包含提交表單所有數(shù)據(jù)的數(shù)組。 $data 數(shù)組對(duì)于像 require_with 這樣需要檢查另一個(gè)提交字段的值作為其結(jié)果基礎(chǔ)的規(guī)則來說十分方便:

public function required_with($str, string $fields, array $data): bool
{
    $fields = explode(',', $fields);

    // If the field is present we can safely assume that
    // the field is here, no matter whether the corresponding
    // search field is present or not.
    $present = $this->required($str ?? '');

    if ($present)
    {
        return true;
    }

    // Still here? Then we fail this test if
    // any of the fields are present in $data
    // as $fields is the lis
    $requiredFields = [];

    foreach ($fields as $field)
    {
        if (array_key_exists($field, $data))
        {
            $requiredFields[] = $field;
        }
    }

    // Remove any keys with empty values since, that means they
    // weren't truly there, as far as this is concerned.
    $requiredFields = array_filter($requiredFields, function ($item) use ($data) {
        return ! empty($data[$item]);
    });

    return empty($requiredFields);
}

自定義錯(cuò)誤可以通過第四個(gè)參數(shù)傳遞,如上所述。

可用規(guī)則?

以下是可供使用的所有本地規(guī)則的列表:

注解

規(guī)則是一個(gè)字符串;參數(shù)之間 不能有空格,尤其是 is_unique 規(guī)則。 ignore_value 前后不能有空格。

// is_unique[table.field,ignore_field,ignore_value]

$validation->setRules([
    'name' => "is_unique[supplier.name,uuid, $uuid]",  // is not ok
    'name' => "is_unique[supplier.name,uuid,$uuid ]",  // is not ok
    'name' => "is_unique[supplier.name,uuid,$uuid]",   // is ok
    'name' => "is_unique[supplier.name,uuid,{uuid}]",  // is ok - see "Validation Placeholders"
]);
Rule Parameter Description Example
alpha No Fails if field has anything other than alphabetic characters.  
alpha_space No Fails if field contains anything other than alphabetic characters or spaces.  
alpha_dash No Fails if field contains anything other than alphanumeric characters, underscores or dashes.  
alpha_numeric No Fails if field contains anything other than alphanumeric characters.  
alpha_numeric_space No Fails if field contains anything other than alphanumeric or space characters.  
alpha_numeric_punct No Fails if field contains anything other than alphanumeric, space, or this limited set of punctuation characters: ~ (tilde), ! (exclamation), # (number), $ (dollar), % (percent), & (ampersand), * (asterisk), - (dash), _ (underscore), + (plus), = (equals), | (vertical bar), : (colon), . (period).  
decimal No Fails if field contains anything other than a decimal number. Also accepts a + or - sign for the number.  
differs Yes Fails if field does not differ from the one in the parameter. differs[field_name]
exact_length Yes Fails if field is not exactly the parameter value. One or more comma-separated values. exact_length[5] or exact_length[5,8,12]
greater_than Yes Fails if field is less than or equal to the parameter value or not numeric. greater_than[8]
greater_than_equal_to Yes Fails if field is less than the parameter value, or not numeric. greater_than_equal_to[5]
hex No Fails if field contains anything other than hexadecimal characters.  
if_exist No If this rule is present, validation will only return possible errors if the field key exists, regardless of its value.  
in_list Yes Fails if field is not within a predetermined list. in_list[red,blue,green]
integer No Fails if field contains anything other than an integer.  
is_natural No Fails if field contains anything other than a natural number: 0, 1, 2, 3, etc.  
is_natural_no_zero No Fails if field contains anything other than a natural number, except zero: 1, 2, 3, etc.  
is_not_unique Yes Checks the database to see if the given value exist. Can ignore records by field/value to filter (currently accept only one filter). is_not_unique[table.field,where_field,where_value]
is_unique Yes Checks if this field value exists in the database. Optionally set a column and value to ignore, useful when updating records to ignore itself. is_unique[table.field,ignore_field,ignore_value]
less_than Yes Fails if field is greater than or equal to the parameter value or not numeric. less_than[8]
less_than_equal_to Yes Fails if field is greater than the parameter value or not numeric. less_than_equal_to[8]
matches Yes The value must match the value of the field in the parameter. matches[field]
max_length Yes Fails if field is longer than the parameter value. max_length[8]
min_length Yes Fails if field is shorter than the parameter value. min_length[3]
numeric No Fails if field contains anything other than numeric characters.  
regex_match Yes Fails if field does not match the regular expression. regex_match[/regex/]
permit_empty No Allows the field to receive an empty array, empty string, null or false.  
required No Fails if the field is an empty array, empty string, null or false.  
required_with Yes The field is required when any of the other required fields are present in the data. required_with[field1,field2]
required_without Yes The field is required when all of the other fields are present in the data but not required. required_without[field1,field2]
string No A generic alternative to the alpha* rules that confirms the element is a string  
timezone No Fails if field does match a timezone per timezone_identifiers_list  
valid_base64 No Fails if field contains anything other than valid Base64 characters.  
valid_json No Fails if field does not contain a valid JSON string.  
valid_email No Fails if field does not contain a valid email address.  
valid_emails No Fails if any value provided in a comma separated list is not a valid email.  
valid_ip No Fails if the supplied IP is not valid. Accepts an optional parameter of ‘ipv4’ or ‘ipv6’ to specify an IP format. valid_ip[ipv6]
valid_url No Fails if field does not contain a valid URL.  
valid_date No Fails if field does not contain a valid date. Accepts an optional parameter to matches a date format. valid_date[d/m/Y]
valid_cc_number Yes Verifies that the credit card number matches the format used by the specified provider. Current supported providers are: American Express (amex), China Unionpay (unionpay), Diners Club CarteBlance (carteblanche), Diners Club (dinersclub), Discover Card (discover), Interpayment (interpayment), JCB (jcb), Maestro (maestro), Dankort (dankort), NSPK MIR (mir), Troy (troy), MasterCard (mastercard), Visa (visa), UATP (uatp), Verve (verve), CIBC Convenience Card (cibc), Royal Bank of Canada Client Card (rbc), TD Canada Trust Access Card (tdtrust), Scotiabank Scotia Card (scotia), BMO ABM Card (bmoabm), HSBC Canada Card (hsbc) valid_cc_number[amex]

文件上傳規(guī)則?

這些驗(yàn)證規(guī)則可以讓你進(jìn)行基本的檢查,驗(yàn)證上傳的文件是否滿足你的業(yè)務(wù)需求。 由于文件上傳字段在 HTML 字段中不存在,并且存儲(chǔ)在 $_FILES 全局變量中, 因此字段名需要輸入兩次,第一個(gè)用于指定驗(yàn)證的字段,像其他規(guī)則一樣,第二次 作為所有文件上傳規(guī)則的第一個(gè)參數(shù):

// In the HTML
<input type="file" name="avatar">

// In the controller
$this->validate([
    'avatar' => 'uploaded[avatar]|max_size[avatar,1024]'
]);
Rule Parameter Description Example
uploaded Yes Fails if the name of the parameter does not match the name of any uploaded files. uploaded[field_name]
max_size Yes Fails if the uploaded file named in the parameter is larger than the second parameter in kilobytes (kb). max_size[field_name,2048]
max_dims Yes Fails if the maximum width and height of an uploaded image exceed values. The first parameter is the field name. The second is the width, and the third is the height. Will also fail if the file cannot be determined to be an image. max_dims[field_name,300,150]
mime_in Yes Fails if the file’s mime type is not one listed in the parameters. mime_in[field_name,image/png,image/jpg]
ext_in Yes Fails if the file’s extension is not one listed in the parameters. ext_in[field_name,png,jpg,gif]
is_image Yes Fails if the file cannot be determined to be an image based on the mime type. is_image[field_name]

文件驗(yàn)證規(guī)則適用于單個(gè)和多個(gè)文件上傳。

注解

你也可以使用任何最多允許兩個(gè)參數(shù)的本地 PHP 函數(shù), 其中至少需要一個(gè)參數(shù)(傳遞字段數(shù)據(jù))。