Laravel Validator Use (reprint)

Source: Internet
Author: User
Tags dateformat

Original 10. Laravel 4 VerificationPosted 1 years ago (2013-12-21 23:00) Read (1703) | Comments (0) 3 People collection This article, I want to collect likes 1

Team document collaboration features launched, do you hate to write documents?

Laravel Validator

Catalogue [-]

  • How to verify
  • Available validation rules
  • Regex:pattern (Regular)
  • Accepted (yes|no|1)
  • In:foo,bar,... (in rule)
  • Notin:_foo,bar,... (not in rule)
  • Alpha (all letters)
  • Numeric (digital)
  • Alpha_num (Letters | numbers)
  • Alpha_dash (Letter | number | dash | underline)
  • URL (legal URL, not rigorous)
  • Active_url (legal URL, based on CHECKDNSRR)
  • Email (e-mail)
  • Image (Jpeg|png|bmp|gif)
  • Integer (whole number)
  • IP (IP address)
  • Before:date (before a given date)
  • After:date (after a given date)
  • Between:min,max (between Min and Max)
  • Confirmed (two confirmation domains, such as "Two confirmation domains for passwords")
  • Same:field (the same value as the given domain)
  • Size:value (the same size as the value of a given field)
  • Date (legal date string, based on Strtotime)
  • Dateformat:_format (Format y-m-d h:i:s)
  • Different:field (differs from)
  • Min:value (minimum value)
  • Max:value (maximum value)
  • Mimes:foo,bar,... (MIME type limit)
  • Base use of MIME rules
  • Required (required)
  • Requiredif:_field,value (required when the specified field is a value)
  • Requiredwith:_foo,bar,... (Required when the specified domain exists)
  • Requiredwithout:_foo,bar,... (Required when the specified domain does not exist)
  • Exists:table,column (must be present in the column field data for table tables)
  • Basic use of Exists rules
  • Unique:table,column,except,idcolumn (Database unique)
  • Basic use of Unique rules
  • How to get error messages
  • Constructed as JSON data (API)
  • Redirect, delivered directly to the next page
  • How to get the error message passed in the view
  • Gets the first error message for a domain
  • Get all error messages for a domain
  • Get all error messages for all domains
  • Check if a domain has a message
  • Get an error message in some format
  • Get all error messages in some format
  • Customizing validation rules
  • customizing validation messages
How to verify

A typical registration form:

<!-- 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() }}

Routing section:

// app/routes.phpRoute::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(‘/‘);});
Available validation rules Regex:pattern (regular)

Verify that the value of this rule must conform to the given regular expression.

Accepted (yes|no|1)

Verify that the value of this rule must be yes, on, or 1. This is useful when verifying that you agree to the terms of service.

In:foo,bar,... (in rule)

Verify that the value of this rule must exist in the given list.

Notin:_foo,bar,... (not in rule)

Verify that the value of this rule must not exist in the given list.

Alpha (all letters)

Verify that the values for this rule must all consist of alphabetic characters.

Numeric (digital)

Verify that the value of this rule must be a number.

Alpha_num (Letters | numbers)

Verify that the value of this rule must consist entirely of letters and numbers.

Alpha_dash (Letter | number | dash | underline)

Verify that the values for this rule must all consist of letters, numbers, dashes, or underscore characters.

URL (legal URL, not rigorous)

Verify that the value of this rule must be a valid URL.
Note: This rule has been confirmed to be not rigorous, similar 2http://url.com URLs can be verified.

Active_url (legal URL, based on CHECKDNSRR)

Verify that the value of this rule must be a valid URL, according to the PHP function CHECKDNSRR.
Note: because it is based on CHECKDNSRR, it can also be used to verify that the mailbox address exists.

Email (e-mail)

Verify that the value of this rule must be a legitimate e-mail address.

Image (Jpeg|png|bmp|gif)

Verify that the value of this rule must be a picture (JPEG, PNG, BMP, or GIF).

Integer (whole number)

Verify that the value of this rule must be an integer.

IP (IP address)

Verify that the value of this rule must be a valid IP address.

Before:date (before a given date)

Verify that the value of this rule must precede the given date and the date will pass through the PHP function Strtotime.

After:date (after a given date)

Verify that the value of this rule must be passed after a given date, and the date will pass through the PHP function Strtotime.

Between:min,max (between Min and Max)

Verify that the value of this rule must be between the given Min and Max. strings, numbers, and files are compared using size rules.

Confirmed (two confirmation domains, such as "Two confirmation domains for passwords")

Verify that the value of this rule must be the same as the value of foo_confirmation. For example, the domain that needs to verify this rule is password, so there must be an identical password_confirmation domain in the input.

Same:field (the same value as the given domain)

Verify that the value of this rule must be the same as the value of the given domain.

Size:value (the same size as the value of a given field)

Verify that the value of this rule must be the same size as the given value.
For a string, value represents the number of characters,
For a number, value represents its integer value,
For a file, value represents the size of the file in kilobytes.

Date (legal date string, based on Strtotime)

Verify that the value of this rule must be a valid date, according to the PHP function Strtotime.

Dateformat:_format (Format y-m-d h:i:s)

Verify that 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 (differs from)

Verify that the value of this rule must be different from the value of the specified field field.

Min:value (minimum value)

Verify that the value of this rule must be greater than the minimum value. strings, numbers, and files are compared using size rules.

Max:value (maximum value)

Verify that the value of this rule must be less than the maximum value. strings, numbers, and files are compared using size rules.

Mimes:foo,bar,... (MIME type limit)

The MIME type of the file that validates this rule must be in the given list.

Base use of MIME rules
‘photo‘ => ‘mimes:jpeg,bmp,png‘

Note: When using regex mode, it is necessary to use arrays to specify rules instead of pipe separators, especially when a pipe character is included in a regular expression.

Required (required)

Verify that the value of this rule must exist in the input data.

Requiredif:_field,value (required when the specified field is a value)

When the specified field is a value, verify that the value of this rule must exist.

Requiredwith:_foo,bar,... (Required when the specified domain exists)

Verify that the value of this rule must exist only if the specified domain exists.

Requiredwithout:_foo,bar,... (Required when the specified domain does not exist)

Verify that the value of this rule must exist only if the specified domain does not exist.

Exists:table,column (must be present in the column field data for table tables)

Verify that the value of this rule must exist in the table of the specified database.

Basic use of Exists rules
‘state‘ => ‘exists:states‘

Specify Column Name

‘state‘ => ‘exists:states,abbreviation‘

You can also specify more criteria that will be added to the query in the form of "where."

‘email‘ => ‘exists:staff,email,account_id,1‘
Unique:table,column,except,idcolumn (Database unique)

Verify that the value of this rule must be unique in the table of the given database. If column is not specified, the name of the field is used.

Basic use of Unique rules
‘email‘ => ‘unique:users‘

Specify Column Name

‘email‘ => ‘unique:users,email_address‘

Forces a given ID to be ignored

‘email‘ => ‘unique:users,email_address,10‘

Add an additional where statement
You can also specify more criteria that will be added to the "where" statement in the query:

‘email‘ => ‘unique:users,email_address,NULL,id,account_id,1

In the above rule, only rows with a account_id of 1 will be included in the unique check.

How to get error messages constructed as JSON data (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);});
Redirect, delivered directly to the next page
return Redirect::to(‘/‘)->withErrors($validator);
How to get the error message passed in the view

Note: $errors is a system-predefined variable that can be used in any template.

Gets the first error message for a domain
{{ $errors->first(‘username‘) }}
Get all error messages for a domain
@foreach($errors->get(‘username‘) as $message)    <li>{{ $message }}</li>@endforeach
Get all error messages for all domains
@foreach($errors->all() as $message)    <li>{{ $message }}</li>@endforeach
Check if a domain has a message
@if($errors->has(‘email‘))    <p>Yey, an error!</p>@endif
Get an error message in some format
{{ $errors->first(‘username‘, ‘<span class="error">:message</span>‘) }}

Note: By default, messages are formatted with BOOTSTRAP-compatible syntax.

Get all error messages in some format
@foreach($errors->all(‘<li>:message</li>‘) as $message)    {{ $message }}@endforeach
Customizing validation rules

Note: anonymous functions and rule extensions that point to normal class methods are not recommended, so you can directly extend the official validator.

To write an extension validator class:

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);    }}

To register a custom validator extension:

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

Please refer to the official category for detailed writing methods. /vendor/laravel/framework/src/Illuminate/Validation/Validator.php

customizing validation messages

For a validation rule:

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

A rule for a specified domain:

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

Defined in the language file /app/lang/zh-CN/validation.php :

‘custom‘ => array(    ‘email‘ => array(        ‘required‘ => ‘请填写您的 email 地址。‘,    ),),

Laravel Validator Use (reprint)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.