Home  >  Article  >  php教程  >  Laravel framework form validation detailed explanation

Laravel framework form validation detailed explanation

高洛峰
高洛峰Original
2016-12-27 10:55:331307browse

Basic 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(&#39;email&#39;, &#39;<p>:message</p>&#39;);

Note: By default, messages will be formatted using Bootstrap-compatible syntax.

Get all error messages in some format

  foreach ($messages->all(&#39;<li>:message</li>&#39;) 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(&#39;register&#39;, function()
{
return View::make(&#39;user.register&#39;);
});
Route::post(&#39;register&#39;, function()
{
$rules = array(...);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails())
{
return Redirect::to(&#39;register&#39;)->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(&#39;email&#39;); ?>

 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

&#39;state&#39; => &#39;exists:states&#39;

Specify column names

&#39;state&#39; => &#39;exists:states,abbreviation&#39;

You can also specify more conditions, which will be added to the query in the form of "where".

&#39;email&#39; => &#39;exists:staff,email,account_id,1&#39;

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 规则的基础使用

&#39;photo&#39; => &#39;mimes:jpeg,bmp,png&#39;

min:value
  验证此规则的值必须大于最小值 value。字符串、数字以及文件都将使用大小规则进行比较。

not_in:foo,bar,...

  验证此规则的值必须在给定的列表中不存在。

numeric

  验证此规则的值必须是一个数字。

regex:pattern

  验证此规则的值必须符合给定的正则表达式。

  注意: 当使用 regex 模式的时候,有必要使用数组指定规则,而不是管道分隔符,特别是正则表达式中包含一个管道字符的时候。

required

  验证此规则的值必须在输入数据中存在。

required_if:field,value

  当指定的域为某个值的时候,验证此规则的值必须存在。

required_with:foo,bar,...

  仅当指定的域存在的时候,验证此规则的值必须存在。

required_without:foo,bar,...

  仅当指定的域不存在的时候,验证此规则的值必须存在。

same:field

  验证此规则的值必须与给定域的值相同。

size:value

验证此规则的值的大小必须与给定的 value 相同。对于字符串,value 代表字符的个数;对于数字,value 代表它的整数值,对于文件,value 代表文件以KB为单位的大小。

unique:table,column,except,idColumn

验证此规则的值必须在给定的数据库的表中唯一。如果 column 没有被指定,将使用该域的名字。

Unique 规则的基础使用

&#39;email&#39; => &#39;unique:users&#39;
指定列名
&#39;email&#39; => &#39;unique:users,email_address&#39;
强制忽略一个给定的 ID
&#39;email&#39; => &#39;unique:users,email_address,10&#39;

url

  验证此规则的值必须是一个合法的 URL。

  定制错误消息

  如果有需要,您可以使用定制的错误消息代替默认的消息。这里有好几种定制错误消息的方法。

  传递定制消息到验证器

$messages = array(
 &#39;required&#39; => &#39;The :attribute field is required.&#39;,
 );
 $validator = Validator::make($input, $rules, $messages);

注意: :attribute 占位符将被实际的进行验证的域的名字代替,您也可以在错误消息中使用其他占位符。

其他验证占位符

  $messages = array(
  &#39;same&#39; => &#39;The :attribute and :other must match.&#39;,
  &#39;size&#39; => &#39;The :attribute must be exactly :size.&#39;,
  &#39;between&#39; => &#39;The :attribute must be between :min - :max.&#39;,
  &#39;in&#39; => &#39;The :attribute must be one of the following types: 
:values&#39;,
  );

  有些时候,您可能希望只对一个指定的域指定定制的错误消息:

  对一个指定的域指定定制的错误消息

$messages = array(
&#39;email.required&#39; => &#39;We need to know your e-mail address!&#39;,
);

在一些情况下,您可能希望在一个语言文件中指定错误消息而不是直接传递给 Validator。为了实现这个目的,请在 app/lang/xx/validation.php 文件中添加您的定制消息到 custom 数组。

在语言文件中指定错误消息

&#39;custom&#39; => array(
&#39;email&#39; => array(
&#39;required&#39; => &#39;We need to know your e-mail address!&#39;,
),
),

定制验证规则

Laravel 提供了一系列的有用的验证规则;但是,您可能希望添加自己的验证规则。其中一种方法是使用 Validator::extend 函数注册定制的验证规则:

注册一个定制的验证规则

Validator::extend(&#39;foo&#39;, function($attribute, $value, $parameters)
{
return $value == &#39;foo&#39;;
});

注意: 传递给 extend 函数的规则的名字必须符合 "snake cased" 命名规则。

  定制的验证器接受三个参数:待验证属性的名字、待验证属性的值以及传递给这个规则的参数。

  您也可以传递一个类的函数到 extend 函数,而不是使用闭包:

  Validator::extend(&#39;foo&#39;, &#39;FooValidator@validate&#39;);

  注意您需要为您的定制规则定义错误消息。您既可以使用一个行内的定制消息数组,也可以在验证语言文件中进行添加。

  您也可以扩展 Validator 类本身,而不是使用闭包回调扩展验证器。为了实现这个目的,添加一个继承自 Illuminate\Validation\Validator 的验证器类。您可以添加在类中添加以 validate 开头的验证函数:

扩展验证器类

<?php
class CustomValidator extends Illuminate\Validation\Validator {
public function validateFoo($attribute, $value, $parameters)
{
return $value == &#39;foo&#39;;
}
}

下面,您需要注册定制的验证器扩展:

您需要注册定制的验证器扩展

Validator::resolver(function($translator, $data, $rules, $messages)
{
return new CustomValidator($translator, $data, $rules, $messages);
});

  当创建一个定制的验证规则,您有时需要为错误消息定义一个定制的占位符。为了实现它,您可以像上面那样创建一个定制的验证器,并且在验证器中添加一个 replaceXXX 函数:

protected function replaceFoo($message, $attribute, $rule, $parameters)
{
return str_replace(&#39;:foo&#39;, $parameters[0], $message);
}

更多Laravel框架表单验证详解相关文章请关注PHP中文网!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn