本文转载自
zhengzizhi
查看原文
2017-08-03
2
ThinkPHP5/
验证/
php/
php5/
thinkphp/
表单
驗證錯誤信息
到目前為止你看到的錯誤提示都是系統內置的,其實大部分驗證規則的錯誤提示只是字段名沒有定義,
我們可以簡單定義下字段描述信息,就基本可以滿足大部分的驗證錯誤提示了。
<?php
namespace app\index\controller;
use think\Controller;
use think\Request;
class Index extends Controller
{
public function index(Request $request)
{
// 定義表單驗證規則
$rules = [
'name|名稱' => 'require|max:25',
'email|郵箱' => 'email',
];
// 驗證表單數據
$result = $this->validate($request->param(), $rules);
if (true !== $result) {
// 驗證失敗 輸出錯誤信息
return '數據驗證失敗:' . $result;
} else {
return '數據驗證通過!';
}
}
}
測試郵箱錯誤的提示信息有所變化:
如果有必要,你也可以完整定義自己的錯誤信息,例如:
<?php
namespace app\index\controller;
use think\Controller;
use think\Request;
class Index extends Controller
{
public function index(Request $request)
{
// 定義表單驗證規則
$rules = [
'name' => 'require|max:25',
'email' => 'email',
];
$msg = [
'name' => ['require' => '名稱必須', 'max' => '名稱超過最大長度'],
'email' => '郵箱格式錯誤',
];
// 驗證表單數據
$result = $this->validate($request->param(), $rules, $msg);
if (true !== $result) {
// 驗證失敗 輸出錯誤信息
return '數據驗證失敗:' . $result;
} else {
return '數據驗證通過!';
}
}
}
V5.0.4版本之前,錯誤信息的定義必須使用下面的方式替代:
<?php
namespace app\index\controller;
use think\Controller;
use think\Request;
class Index extends Controller
{
public function index(Request $request)
{
// 定義表單驗證規則
$rules = [
'name' => 'require|max:25',
'email' => 'email',
];
$msg = [
'name.require' => '名稱必須',
'name.max' => '名稱超過最大長度',
'email' => '郵箱格式錯誤',
];
// 驗證表單數據
$result = $this->validate($request->param(), $rules, $msg);
if (true !== $result) {
// 驗證失敗 輸出錯誤信息
return '數據驗證失敗:' . $result;
} else {
return '數據驗證通過!';
}
}
}
當我們的name值輸入超過25位后,會提示:名稱超過最大長度
如果你使用的是獨立Validate驗證類的話,可以使用以下代碼:
<?php
namespace app\index\controller;
use think\Request;
use think\Validate;
class Index
{
public function index(Request $request)
{
// 定義表單驗證規則
$rules = [
'name' => 'require|max:25',
'email' => 'email',
];
$msg = [
'name' => ['require' => '名稱必須', 'max' => '名稱超過最大長度'],
'email' => '郵箱格式錯誤',
];
// 驗證表單數據
$validate = new Validate($rules, $msg);
$result = $validate->check($request->param());
if (true !== $result) {
// 驗證失敗 輸出錯誤信息
return '數據驗證失敗:' . $result;
} else {
return '數據驗證通過!';
}
}
}