Laravel framework form validation detailed explanation
Dec 27, 2016 am 10:55 AMBasic verification example
$validator = Validator::make( array('name' => 'Dayle'), array('name' => 'required|min:5') );
The first parameter passed to the make function is the data to be verified, and the second parameter is the verification rule that needs to be applied to the data.
Multiple validation rules can be separated by the "|" character, or as a separate element of an array.
Specify validation rules via array
$validator = Validator::make( array('name' => 'Dayle'), array('name' => array('required', 'min:5')) );
Once a Validator instance is created, you can use the fails (or passes) function to perform the validation.
if ($validator->fails()) { // The given data did not pass validation }
If validation fails, you can get the error message from the validator.
$messages = $validator->messages();
You can also use the failed function to get an array of rules that failed validation without an error message.
$failed = $validator->failed();
File Validation
The Validator class provides some validation rules for validating files, such as size, mimes, etc. When validating a file, you can pass it to the validator just like any other validation.
With error message
After calling the messages function on a Validator instance, you will get a MessageBag instance, which has many convenient functions for handling error messages.
Get the first error message for a domain
echo $messages->first('email');
Get all error messages for a domain
foreach ($messages->get('email') as $message) { // }
Get all error messages for all domains
foreach ($messages->all() as $message) { // }
Check if a message exists for a domain
if ($messages->has('email')) { // }
Get an error message in a certain format
echo $messages->first('email', '<p>:message</p>');
Note: By default, messages will be formatted using Bootstrap-compatible syntax.
Get all error messages in some format
foreach ($messages->all('<li>:message</li>') as $message) { // }
Error Messages & Views
Once you have performed validation, you need an easy way to feed error messages back to the view. This can be easily handled in Lavavel. Take the following route as an example:
Route::get('register', function() { return View::make('user.register'); }); Route::post('register', function() { $rules = array(...); $validator = Validator::make(Input::all(), $rules); if ($validator->fails()) { return Redirect::to('register')->withErrors($validator); } });
Note that when validation fails, we use the withErrors function to pass the Validator instance to Redirect. This function will refresh the error message saved in the Session so that it is available on the next request.
However, note that we do not have to explicitly bind the error message to the route in the GET route. This is because Laravel always checks the Session for errors and automatically binds them to the view if they are available. So, for every request, a $errors variable is always available in all views, allowing you to conveniently assume that $errors is always defined and safe to use. The $errors variable will be an instance of the MessageBag class.
So, after the jump, you can use the automatically bound $errors variable in the view:
<?php echo $errors->first('email'); ?>
?Available validation rules
?The following is a list of all available List of validation rules and their functionality:
Accepted Active URL After (Date) Alpha Alpha Dash Alpha Numeric Before (Date) Between Confirmed Date Date Format Different E-Mail Exists (Database) Image (File) In Integer IP Address Max MIME Types Min Not In Numeric Regular Expression Required Required If Required With Required Without Same Size Unique (Database)
accepted
Validation The value of this rule must be yes, on, or 1. This is useful when verifying agreement with the Terms of Service.
active_url
Validates that the value of this rule must be a valid URL, according to the PHP function checkdnsrr.
after:date
Validates that the value of this rule must be after the given date, which will be passed via the PHP function strtotime.
alpha
The value validating this rule must consist entirely of alphabetic characters.
alpha_dash
The value validating this rule must consist entirely of letters, numbers, dashes, or underline characters.
alpha_num
The value validating this rule must consist entirely of letters and numbers.
before:date
Validate that the value of this rule must be before the given date, the date will be passed through the PHP function strtotime.
between:min,max
Validates that the value of this rule must be between the given min and max. Strings, numbers, and files are compared using size rules.
confirmed
The value of this validation rule must be the same as the value of foo_confirmation. For example, if the field that needs to be validated for this rule is password, there must be an identical password_confirmation field in the input.
date
Validates that the value of this rule must be a valid date, according to the PHP function strtotime.
date_format:format
? Validation The value of this rule must conform to the format of the given format, according to the PHP function date_parse_from_format.
different:field
Validate that the value of this rule must be different from the value of the specified field field.
email
Verify that the value of this rule must be a valid email address.
exists:table,column
Validates that the value of this rule must exist in the table of the specified database.
The basis of the Exists rule uses
'state' => 'exists:states'
Specify column names
'state' => 'exists:states,abbreviation'
You can also specify more conditions, which will be added to the query in the form of "where".
'email' => 'exists:staff,email,account_id,1'
image
The value validating this rule must be an image (jpeg, png, bmp or gif).
in:foo,bar,...
Validates that the value of this rule must exist in the given list.
integer
The value validating this rule must be an integer.
Verify that the value of this rule must be a valid IP address.
max:value
The value that validates this rule must be less than the maximum value. Strings, numbers, and files are compared using size rules.
Mimes:foo,bar,...
The MIME type of the file that this rule is validated against must be in the given list.
MIME 規(guī)則的基礎(chǔ)使用
'photo' => 'mimes:jpeg,bmp,png'
min:value
驗(yàn)證此規(guī)則的值必須大于最小值 value。字符串、數(shù)字以及文件都將使用大小規(guī)則進(jìn)行比較。
not_in:foo,bar,...
驗(yàn)證此規(guī)則的值必須在給定的列表中不存在。
numeric
驗(yàn)證此規(guī)則的值必須是一個(gè)數(shù)字。
regex:pattern
驗(yàn)證此規(guī)則的值必須符合給定的正則表達(dá)式。
注意: 當(dāng)使用 regex 模式的時(shí)候,有必要使用數(shù)組指定規(guī)則,而不是管道分隔符,特別是正則表達(dá)式中包含一個(gè)管道字符的時(shí)候。
required
驗(yàn)證此規(guī)則的值必須在輸入數(shù)據(jù)中存在。
required_if:field,value
當(dāng)指定的域?yàn)槟硞€(gè)值的時(shí)候,驗(yàn)證此規(guī)則的值必須存在。
required_with:foo,bar,...
僅當(dāng)指定的域存在的時(shí)候,驗(yàn)證此規(guī)則的值必須存在。
required_without:foo,bar,...
僅當(dāng)指定的域不存在的時(shí)候,驗(yàn)證此規(guī)則的值必須存在。
same:field
驗(yàn)證此規(guī)則的值必須與給定域的值相同。
size:value
驗(yàn)證此規(guī)則的值的大小必須與給定的 value 相同。對(duì)于字符串,value 代表字符的個(gè)數(shù);對(duì)于數(shù)字,value 代表它的整數(shù)值,對(duì)于文件,value 代表文件以KB為單位的大小。
unique:table,column,except,idColumn
驗(yàn)證此規(guī)則的值必須在給定的數(shù)據(jù)庫(kù)的表中唯一。如果 column 沒(méi)有被指定,將使用該域的名字。
Unique 規(guī)則的基礎(chǔ)使用
'email' => 'unique:users' 指定列名 'email' => 'unique:users,email_address' 強(qiáng)制忽略一個(gè)給定的 ID 'email' => 'unique:users,email_address,10'
url
驗(yàn)證此規(guī)則的值必須是一個(gè)合法的 URL。
定制錯(cuò)誤消息
如果有需要,您可以使用定制的錯(cuò)誤消息代替默認(rèn)的消息。這里有好幾種定制錯(cuò)誤消息的方法。
傳遞定制消息到驗(yàn)證器
$messages = array( 'required' => 'The :attribute field is required.', ); $validator = Validator::make($input, $rules, $messages);
注意: :attribute 占位符將被實(shí)際的進(jìn)行驗(yàn)證的域的名字代替,您也可以在錯(cuò)誤消息中使用其他占位符。
其他驗(yàn)證占位符
$messages = array( 'same' => 'The :attribute and :other must match.', 'size' => 'The :attribute must be exactly :size.', 'between' => 'The :attribute must be between :min - :max.', 'in' => 'The :attribute must be one of the following types: :values', );
有些時(shí)候,您可能希望只對(duì)一個(gè)指定的域指定定制的錯(cuò)誤消息:
對(duì)一個(gè)指定的域指定定制的錯(cuò)誤消息
$messages = array( 'email.required' => 'We need to know your e-mail address!', );
在一些情況下,您可能希望在一個(gè)語(yǔ)言文件中指定錯(cuò)誤消息而不是直接傳遞給 Validator。為了實(shí)現(xiàn)這個(gè)目的,請(qǐng)?jiān)?app/lang/xx/validation.php 文件中添加您的定制消息到 custom 數(shù)組。
在語(yǔ)言文件中指定錯(cuò)誤消息
'custom' => array( 'email' => array( 'required' => 'We need to know your e-mail address!', ), ),
定制驗(yàn)證規(guī)則
Laravel 提供了一系列的有用的驗(yàn)證規(guī)則;但是,您可能希望添加自己的驗(yàn)證規(guī)則。其中一種方法是使用 Validator::extend 函數(shù)注冊(cè)定制的驗(yàn)證規(guī)則:
注冊(cè)一個(gè)定制的驗(yàn)證規(guī)則
Validator::extend('foo', function($attribute, $value, $parameters) { return $value == 'foo'; });
注意: 傳遞給 extend 函數(shù)的規(guī)則的名字必須符合 "snake cased" 命名規(guī)則。
定制的驗(yàn)證器接受三個(gè)參數(shù):待驗(yàn)證屬性的名字、待驗(yàn)證屬性的值以及傳遞給這個(gè)規(guī)則的參數(shù)。
您也可以傳遞一個(gè)類(lèi)的函數(shù)到 extend 函數(shù),而不是使用閉包:
Validator::extend('foo', 'FooValidator@validate');
注意您需要為您的定制規(guī)則定義錯(cuò)誤消息。您既可以使用一個(gè)行內(nèi)的定制消息數(shù)組,也可以在驗(yàn)證語(yǔ)言文件中進(jìn)行添加。
您也可以擴(kuò)展 Validator 類(lèi)本身,而不是使用閉包回調(diào)擴(kuò)展驗(yàn)證器。為了實(shí)現(xiàn)這個(gè)目的,添加一個(gè)繼承自 Illuminate\Validation\Validator 的驗(yàn)證器類(lèi)。您可以添加在類(lèi)中添加以 validate 開(kāi)頭的驗(yàn)證函數(shù):
擴(kuò)展驗(yàn)證器類(lèi)
<?php class CustomValidator extends Illuminate\Validation\Validator { public function validateFoo($attribute, $value, $parameters) { return $value == 'foo'; } }
下面,您需要注冊(cè)定制的驗(yàn)證器擴(kuò)展:
您需要注冊(cè)定制的驗(yàn)證器擴(kuò)展
Validator::resolver(function($translator, $data, $rules, $messages) { return new CustomValidator($translator, $data, $rules, $messages); });
當(dāng)創(chuàng)建一個(gè)定制的驗(yàn)證規(guī)則,您有時(shí)需要為錯(cuò)誤消息定義一個(gè)定制的占位符。為了實(shí)現(xiàn)它,您可以像上面那樣創(chuàng)建一個(gè)定制的驗(yàn)證器,并且在驗(yàn)證器中添加一個(gè) replaceXXX 函數(shù):
protected function replaceFoo($message, $attribute, $rule, $parameters) { return str_replace(':foo', $parameters[0], $message); }
更多Laravel框架表單驗(yàn)證詳解相關(guān)文章請(qǐng)關(guān)注PHP中文網(wǎng)!

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)
