如何進行驗證
典型的注冊表單:
<!-- app/views/form.blade.php -->
{{ Form::open(array('url' => 'registration')) }} {{-- Username field. ------------------------}} {{ Form::label('username', 'Username') }} {{ Form::text('username') }} {{-- Email address field. -------------------}} {{ Form::label('email', 'Email address') }} {{ Form::email('email') }} {{-- Password field. ------------------------}} {{ Form::label('password', 'Password') }} {{ Form::password('password') }} {{-- Password confirmation field. -----------}} {{ Form::label('password_confirmation', 'Password confirmation') }} {{ Form::password('password_confirmation') }} {{-- Form submit button. --------------------}} {{ Form::submit('Register') }} {{ Form::close() }}
路由部分:
// app/routes.php Route::get('/', function() { return View::make('form'); }); Route::post('/registration', function() { // 獲取所有表單數據. $data = Input::all(); // 創建驗證規則 $rules = array( 'username' => array('alpha_num', 'min:3') ); // 開始驗證 $validator = Validator::make($data, $rules); if ($validator->passes()) { // 驗證成功 return 'Data was saved.'; } // 驗證失敗 return Redirect::to('/'); });
可用的驗證規則
regex:pattern(正則)
驗證此規則的值必須符合給定的正則表達式。
accepted(yes|no|1)
驗證此規則的值必須是 yes、 on 或者是 1。這在驗證是否同意"服務條款"的時候非常有用。
in:foo,bar,...(in 規則)
驗證此規則的值必須在給定的列表中存在。
notin:_foo,bar,...(not in 規則)
驗證此規則的值必須在給定的列表中不存在。
alpha(全部字母)
驗證此規則的值必須全部由字母字符構成。
numeric(數字)
驗證此規則的值必須是一個數字。
alpha_num(字母|數字)
驗證此規則的值必須全部由字母和數字構成。
alpha_dash(字母|數字|中划線|下划線)
驗證此規則的值必須全部由字母、數字、中划線或下划線字符構成。
url(合法 URL,不嚴謹)
驗證此規則的值必須是一個合法的 URL。
注意: 已經證實此規則不嚴謹,類似 2http://url.com
的 URL 可以通過驗證。
active_url(合法 URL,基於 checkdnsrr)
驗證此規則的值必須是一個合法的 URL,根據 PHP 函數 checkdnsrr。
注意: 由於是基於 checkdnsrr 因此也可用於驗證郵箱地址是否存在。
email(電子郵件)
驗證此規則的值必須是一個合法的電子郵件地址。
image (jpeg|png|bmp|gif)
驗證此規則的值必須是一個圖片 (jpeg, png, bmp 或者 gif)。
integer(整數)
驗證此規則的值必須是一個整數。
ip(IP 地址)
驗證此規則的值必須是一個合法的 IP 地址。
before:date(給定日期之前)
驗證此規則的值必須在給定日期之前,日期將通過 PHP 函數 strtotime 傳遞。
after:date(給定日期之后)
驗證此規則的值必須在給定日期之后,日期將通過 PHP 函數 strtotime 傳遞。
between:min,max(min 和 max 之間)
驗證此規則的值必須在給定的 min 和 max 之間。字符串、數字以及文件都將使用大小規則進行比較。
confirmed(二次確認域,如“密碼的二次確認域”)
驗證此規則的值必須和 foo_confirmation 的值相同。比如,需要驗證此規則的域是 password,那么在輸入中必須有一個與之相同的 password_confirmation 域。
same:field(值與給定域相同)
驗證此規則的值必須與給定域的值相同。
size:value(大小與給定域的值相同)
驗證此規則的值的大小必須與給定的 value 相同。
對於字符串,value 代表字符的個數,
對於數字,value 代表它的整數值,
對於文件,value 代表文件以KB為單位的大小。
date(合法日期字符串,基於 strtotime)
驗證此規則的值必須是一個合法的日期,根據 PHP 函數 strtotime。
dateformat:_format(format 格式 y-m-d H:i:s)
驗證此規則的值必須符合給定的 format 的格式,根據 PHP 函數 date_parse_from_format。
different:field(不同於)
驗證此規則的值必須與指定的 field 域的值不同。
min:value(最小值)
驗證此規則的值必須大於最小值 value。字符串、數字以及文件都將使用大小規則進行比較。
max:value(最大值)
驗證此規則的值必須小於最大值 value。字符串、數字以及文件都將使用大小規則進行比較。
mimes:foo,bar,...(MIME 類型限制)
驗證此規則的文件的 MIME 類型必須在給定的列表中。
MIME 規則的基礎使用
'photo' => 'mimes:jpeg,bmp,png'
注意: 當使用 regex 模式的時候,有必要使用數組指定規則,而不是管道分隔符,特別是正則表達式中包含一個管道字符的時候。
required(必填)
驗證此規則的值必須在輸入數據中存在。
requiredif:_field,value(當指定域為某個值時,必填)
當指定的域為某個值的時候,驗證此規則的值必須存在。
requiredwith:_foo,bar,...(當指定域存在時,必填)
僅當指定的域存在的時候,驗證此規則的值必須存在。
requiredwithout:_foo,bar,...(當指定域不存在時,必填)
僅當指定的域不存在的時候,驗證此規則的值必須存在。
exists:table,column(必須存在於 table 表的 column 字段數據中)
驗證此規則的值必須在指定的數據庫的表中存在。
Exists 規則的基礎使用
'state' => 'exists:states'
指定列名
'state' => 'exists:states,abbreviation'
您也可以指定更多的條件,將以 "where" 的形式添加到查詢。
'email' => 'exists:staff,email,account_id,1'
unique:table,column,except,idColumn(數據庫唯一)
驗證此規則的值必須在給定的數據庫的表中唯一。如果 column 沒有被指定,將使用該域的名字。
Unique 規則的基礎使用
'email' => 'unique:users'
指定列名
'email' => 'unique:users,email_address'
強制忽略一個給定的 ID
'email' => 'unique:users,email_address,10'
添加額外的where語句
你還可以指定更多條件,這些條件將被添加到查詢的"where"語句中:
'email' => 'unique:users,email_address,NULL,id,account_id,1
在上面的規則中,只有account_id 為 1 的行才會被包含到unique檢查中。
如何獲取錯誤消息
構造為 JSON 數據(API)
Route::post('/registration', function() { // 獲取全部提交數據 $data = Input::all(); // 構造規則數組 $rules = array( 'username' => 'alpha_num' ); // 開始驗證 $validator = Validator::make($data, $rules); if ($validator->passes()) { // 驗證通過 return 'Data was saved.'; } // 驗證失敗 // 獲取錯誤消息 $errors = $validator->messages(); // 構造 JSON 響應 return Response::json($errors); });
重定向,直接傳遞至下一個頁面
return Redirect::to('/')->withErrors($validator);
視圖中如何獲取傳遞過來的錯誤消息
注意: $errors
是系統預定義變量,任何模板中均可使用。
獲取一個域的第一個錯誤消息
{{ $errors->first('username') }}
獲取一個域的全部錯誤消息
@foreach($errors->get('username') as $message) <li>{{ $message }}</li> @endforeach
獲取全部域的全部錯誤消息
@foreach($errors->all() as $message) <li>{{ $message }}</li> @endforeach
檢查一個域是否存在消息
@if($errors->has('email')) <p>Yey, an error!</p> @endif
以某種格式獲取一條錯誤消息
{{ $errors->first('username', '<span class="error">:message</span>') }}
注意: 默認情況下,消息將使用與 Bootstrap 兼容的語法進行格式化。
以某種格式獲取所有錯誤消息
@foreach($errors->all('<li>:message</li>') as $message) {{ $message }} @endforeach
定制驗證規則
注意: 匿名函數 和 指向普通類方法 的 規則擴展 並不推薦,因此直接介紹如何直接擴展官方的驗證器。
編寫擴展驗證器類:
class ExValidator extends Illuminate\Validation\Validator { // 規則 public function validateFoo($attribute, $value, $parameters) { return $value == 'foo'; } // 消息 protected function replaceFoo($message, $attribute, $rule, $parameters) { return str_replace(':foo', $parameters[0], $message); } }
注冊定制的驗證器擴展:
Validator::resolver(function($translator, $data, $rules, $messages) { return new ExValidator($translator, $data, $rules, $messages); });
詳細的編寫方法請參照官方類 /vendor/laravel/framework/src/Illuminate/Validation/Validator.php
。
定制驗證消息
針對某一個驗證規則:
$messages = array( 'required' => 'The :attribute field is required.', ); $validator = Validator::make($input, $rules, $messages);
針對指定域的某一規則:
$messages = array( 'email.required' => 'We need to know your e-mail address!', );
在語言文件中定義 /app/lang/zh-CN/validation.php
:
'custom' => array( 'email' => array( 'required' => '請填寫您的 email 地址。', ), ),
原文:http://my.oschina.net/5say/blog/186568
我個人更喜歡使用Request方式進行驗證;使用laravel的artisan命令 php artisan make:request XxxxxRequest.php中進行驗證
使用request驗證的好處是可以 表單使用ajax提交的時候 框架會自動返回json錯誤消息,其他提交方式 框架仍然使用$message返回