Laravel 5系列教程七:表單驗證 Validation
Jun 20, 2016 pm 12:49 PM原文來自:https://laravist.com/article/15
Laravist是我剛剛上線的Laravel社區(qū),有任何與Laravel相關(guān)的問題可以到這里來問我,我會盡力去幫大家解決問題,后期會嘗試錄制一些視頻教程,形式大概是這樣的
https://laravist.com/lesson/1
終于要更新這個Laravel系列教程的第七篇了,期間去寫了一點其他的東西。
就不說廢話了吧,直接進入Form Validation的部分吧。幾乎在每一個web應用當中都會有表單,而有表單基本就離不開表單驗證。在laravel中,其實可以說是有兩種方式來進行表單驗證:使用Request和使用Validation。下面將分開講這兩部分的內(nèi)容,而且我會更著重第一種,也更推薦大家使用第一種進行表單驗證:
Request表單驗證
為什么說是會把精力都放在講解第一種驗證方式呢?因為個人覺得第一種方式在相同的驗證條件下,更加易于維護和可以進行代碼重用。而且寫代碼的形式更適用于Laravel和我個人的使用習慣:可以使用命令行來生成代碼。也就是可以使用artisan這個工具:
php artisan make:request StoreArticleRequest
在項目目錄下使用artisan的make:request命令就可以生成一個用于表單驗證Request類了,這個類我們在這里命名為StoreArticleRequest,你也可以以你自己喜歡的方式來命名,但我還是推薦大家在命名的時候盡量使得名字比較人性化一點,這樣會比較對于后期再看代碼的時候有很多好處。這個命令生成的文件位于app/Http/Requests/這個文件夾當中,我們打開這個文件來看:
class StoreArticleRequest extends Request{ /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return false; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ // ]; }}
實現(xiàn)驗證
可以看到里面會有兩個方法:authorize()和 rules() 。authorize()可以這樣簡單地理解:我們在處理這個表單請求(通常是一個post請求)的時候是否是需要進行身份驗證,這種驗證是指:比如A發(fā)表的評論,B能不能進行編輯。如果不能,則保留返回false,如果可以,則修改返回true。那么我們這里的邏輯是:既然是發(fā)表文章,在我們這個站點注冊的用戶(如果開放注冊的話)都是可以發(fā)表文章的,所以我們首先修改authorize()方法,將其返回值改為:return true;。
然后對于rules()方法,我們需要在這里設(shè)置我們的驗證規(guī)則,比如我們可以設(shè)置下面這個的驗證規(guī)則:
public function rules() { return [ 'title' => 'required', 'content' => 'required' ]; }
因為我們在創(chuàng)建文章的時候,我們會有兩個提交過來的字段:title和content。這是我們在設(shè)計articles表的時候設(shè)置的兩個字段。
然后,上面的驗證規(guī)則是:對于title和content兩個字段,我們需要用戶為其填充內(nèi)容,不能為空。
既然這里的規(guī)則設(shè)置好之后,我們該怎么應用起來呢?也就是我們怎么在將文章存入數(shù)據(jù)庫之前進行驗證呢?很簡單,我們只需要稍微修改ArticleController的store()方法:
public function store(Requests\StoreArticleRequest $request) { $input = $request->all(); //下面增加兩行,順便看看Request::get的使用 $input['intro'] = mb_substr($request->get('content'),0,64); }
我們將整個StoreArticleRequest類的實例以$request變量傳入store()方法,這個時候,laravel
就會自動檢查我們是否需要進行表單驗證(rules方法有沒有定義驗證規(guī)則),如果有需要驗證的話,laravel會首先走驗證這條路,如果驗證沒有通過,store()方法內(nèi)的代碼不會被執(zhí)行,而是直接跳轉(zhuǎn)到提交表單的頁面,這里是:http://blog.dev/article/create 這個頁面。如果所有的驗證都通過之后,才會執(zhí)行store()內(nèi)部的代碼,也就是才會執(zhí)行到$input = $request->all();這里以及往下的代碼。。。比如我們來試試留空的時候是什么樣的情況:
反饋錯誤
上面的圖片中好像沒有什么變化,但其實是已經(jīng)提交了一次了,但是又馬上跳轉(zhuǎn)回來了。我們可以使用下面的方式來驗證一下:
@if($errors->any()) <ul class="alert alert-danger"> @foreach($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul>@endif
在create.blade.php這個視圖文件中增加上面的代碼,我這里是放在{!! Form::close() !!}后面。這里的意思大概就是,如果有任何表單驗證的錯誤消息,我們就講這個信息打印出來反饋給用戶。如果沒有,則不會顯示信息。我們再來試一下:
這時候可以看到,我們在表單驗證沒有通過的時候,在頁面顯示了相對應的錯誤信息。如果沒有錯誤,就創(chuàng)建一篇文章。
tips:如果你不想錯誤信息為英文,可以到resources/lang/en/validation.php修改,或者你直接創(chuàng)建一個新的語言文件包。
多個驗證規(guī)則
OK,這里,我們基本是將這個這個驗證流程走通了。但是,在實際的開發(fā)中,我們的驗證并不都是這個簡單:要是我們要對一個字段設(shè)置多個驗證規(guī)則呢?比如我們希望文章的title最少不能少于三個字節(jié)長度呢?我們可以這樣,在rules()方法中:
'title' => 'required|min:3',
在laravel中,我們使用|將多個規(guī)則分開,:表示規(guī)則的值。其實這里你也可以使用數(shù)組的,但是我還是推薦大家像上面這樣寫,簡潔明了。
其他常用驗證規(guī)則
至于更多地驗證規(guī)則,比如注冊的時候,驗證一個email和確認密碼的時候,我們怎么需要怎么寫的呢?
'email'=>'required|email','password'=>'required|min:6|confirmed','password_confirmation' => 'required|min:6'
上面我直接給出這兩個常用場景的最常見的寫法,email就代表驗證所填的信息是否是一個正確地郵箱格式了,至于確認密碼就使用confirmed來指定,這里注意是confirmed而不是confirme。而且第二次輸入密碼的字段需要寫成password_confirmation這個形式,也就是在視圖中,我們會有類似這樣的input表單:
<input type="password" name="password" /><input type="password" name="password_confirmation" />
關(guān)于更多驗證規(guī)則,參考官方文檔:
http://laravel.com/docs/5.1/validation
使用Validation
使用這個之前可以將store(Requests\StoreArticleRequest $request)中的變量去掉
使用Validation的時候,多用于驗證一些簡單的表單驗證。這里演示直接寫于ArticleController當中,直接使用Validator::make(),使用方式為Validator::make(array $request,array $rules),比如說我們的例子可以在store()中寫成:
$input = Request::all();$validator = Validator::make($input, [ 'title' => 'required|min:3', 'body' => 'required',]);
然后可以使用下面這樣的方式來檢查驗證有沒有通過:
if ($validator->fails()) { }
驗證通過之后,我們才進行下一步操作,比如將數(shù)據(jù)存入數(shù)據(jù)庫。一個基本的Validation流程就完成了,而且關(guān)于Validation的部分,我也只想介紹到這里,因為我會安利大家使用第一種方式:Request。
tips:這兩種方式的背后都是使用一樣的驗證機制。
總結(jié)
這里就基本將基礎(chǔ)的表單驗證說完了,下一節(jié)我準說說queryScope和SetAttributes的使用,這兩個對于我們的數(shù)據(jù)入庫的預處理和代碼重用都很有幫助,所以下次會先說這兩個知識點:我們會先對published_at這個字段的設(shè)置和使用發(fā)揮出來,到時候你就知道設(shè)置這個字段的好處了。
最后:Happy Hacking

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

TosecurelyhandleauthenticationandauthorizationinPHP,followthesesteps:1.Alwayshashpasswordswithpassword_hash()andverifyusingpassword_verify(),usepreparedstatementstopreventSQLinjection,andstoreuserdatain$_SESSIONafterlogin.2.Implementrole-basedaccessc

To safely handle file uploads in PHP, the core is to verify file types, rename files, and restrict permissions. 1. Use finfo_file() to check the real MIME type, and only specific types such as image/jpeg are allowed; 2. Use uniqid() to generate random file names and store them in non-Web root directory; 3. Limit file size through php.ini and HTML forms, and set directory permissions to 0755; 4. Use ClamAV to scan malware to enhance security. These steps effectively prevent security vulnerabilities and ensure that the file upload process is safe and reliable.

In PHP, the main difference between == and == is the strictness of type checking. ==Type conversion will be performed before comparison, for example, 5=="5" returns true, and ===Request that the value and type are the same before true will be returned, for example, 5==="5" returns false. In usage scenarios, === is more secure and should be used first, and == is only used when type conversion is required.

The methods of using basic mathematical operations in PHP are as follows: 1. Addition signs support integers and floating-point numbers, and can also be used for variables. String numbers will be automatically converted but not recommended to dependencies; 2. Subtraction signs use - signs, variables are the same, and type conversion is also applicable; 3. Multiplication signs use * signs, which are suitable for numbers and similar strings; 4. Division uses / signs, which need to avoid dividing by zero, and note that the result may be floating-point numbers; 5. Taking the modulus signs can be used to judge odd and even numbers, and when processing negative numbers, the remainder signs are consistent with the dividend. The key to using these operators correctly is to ensure that the data types are clear and the boundary situation is handled well.

Yes, PHP can interact with NoSQL databases like MongoDB and Redis through specific extensions or libraries. First, use the MongoDBPHP driver (installed through PECL or Composer) to create client instances and operate databases and collections, supporting insertion, query, aggregation and other operations; second, use the Predis library or phpredis extension to connect to Redis, perform key-value settings and acquisitions, and recommend phpredis for high-performance scenarios, while Predis is convenient for rapid deployment; both are suitable for production environments and are well-documented.

TostaycurrentwithPHPdevelopmentsandbestpractices,followkeynewssourceslikePHP.netandPHPWeekly,engagewithcommunitiesonforumsandconferences,keeptoolingupdatedandgraduallyadoptnewfeatures,andreadorcontributetoopensourceprojects.First,followreliablesource

PHPbecamepopularforwebdevelopmentduetoitseaseoflearning,seamlessintegrationwithHTML,widespreadhostingsupport,andalargeecosystemincludingframeworkslikeLaravelandCMSplatformslikeWordPress.Itexcelsinhandlingformsubmissions,managingusersessions,interacti

TosettherighttimezoneinPHP,usedate_default_timezone_set()functionatthestartofyourscriptwithavalididentifiersuchas'America/New_York'.1.Usedate_default_timezone_set()beforeanydate/timefunctions.2.Alternatively,configurethephp.inifilebysettingdate.timez
