Laravel Framework Forms Verification detailed _php example

Source: Internet
Author: User
Tags closure naming convention validation examples

Basic validation Examples

Copy Code code as follows:

$validator = Validator::make (
Array (' name ' => ' Dayle '),
Array (' name ' => ' Required|min:5 ')
);

The first parameter passed to the Make function is the data to be validated, and the second parameter is the validation rule that needs to be applied to the data.

Multiple validation rules can be separated by the "|" character, or as a separate element of the array.

Specifying validation rules through arrays

Copy Code code as follows:

$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 this validation.

Copy Code code as follows:

if ($validator->fails ())
{
The given data did not pass validation
}

If the validation fails, you can get the error message from the validator.
Copy Code code as follows:

$messages = $validator->messages ();

You can also use the failed function to get an array with no validation rules without error messages.
Copy Code code as follows:

$failed = $validator->failed ();

File validation

The Validator class provides validation rules for validating files, such as size, mimes, and so on. When validating a file, you can pass it to the validator as you would any other validation.

Accompanying error message

After calling the messages function on a Validator instance, you will get a messagebag instance that has many convenient functions for handling error messages.

Gets the first error message for a domain

Copy Code code as follows:

echo $messages->first (' email ');

Get all error messages for a domain

Copy Code code as follows:

foreach ($messages->get (' email ') as $message)
{
//
}

Get all error messages for all fields

Copy Code code as follows:

foreach ($messages->all () as $message)
{
//
}

Check if a field has a message

Copy Code code as follows:

if ($messages->has (' email '))
{
//
}

Get an error message in some format

Copy Code code as follows:

echo $messages->first (' email ', ' <p>:message</p> ');

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

Get all error messages in some format

Copy Code code as follows:

foreach ($messages->all (' <li>:message</li> ') as $message)
{
//
}

Error Messages & Views

Once you have performed the validation, you need an easy way to feedback the error message to the view. This can be conveniently handled in the Lavavel. Take the following route as an example:

Copy Code code as follows:

Route::get (' register ', function ()
{
Return View::make (' User.register ');
});
Route::p ost (' 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 refreshes the saved error message in the session so that it can be available in the next request.

However, note that we do not need to explicitly bind error messages to routes in get routes. This is because laravel always checks for errors in the session and automatically binds them to the view if they are available. Therefore, for each request, a $errors variable is always available in all views, allowing you to easily think that $errors is always defined and safe to use. $errors variable will be an instance of a Messagebag class.

So, after the jump, you can use the automatically bound $errors variable in the view:

Copy Code code as follows:

<?php echo $errors->first (' email ');?>

Available validation rules

The following is a list of all the validation rules available and their functionality:

Copy Code code as follows:

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

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

Active_url

Verify that the value of this rule must be a valid URL, based on the PHP function CHECKDNSRR.

After:date

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

Alpha
Verify that the value of this rule must consist of all alphabetic characters.

Alpha_dash
Verify that the value of this rule must consist entirely of letters, numbers, dashes, or underscore characters.

Alpha_num
Verify that the value of this rule must be all composed of letters and numbers.

Before:date
Verify that the value of this rule must precede the given date and the date will be passed through the PHP function Strtotime.

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

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

Date
Verify that the value of this rule must be a valid date, based on the PHP function Strtotime.

Date_format:format
Verify that the value of this rule must conform to the format of the given format, based on the PHP function Date_parse_from_format.

Different:field
Verify 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 e-mail address.

Exists:table,column
Verify that the value of this rule must exist in the table of the specified database.

Basic use of Exists rules

Copy Code code as follows:
' State ' => ' exists:states '

Specify column names
Copy Code code as follows:

' State ' => ' exists:states,abbreviation '

You can also specify more criteria that will be added to the query as a "where".
Copy Code code as follows:

' Email ' => ' exists:staff,email,account_id,1 '

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

In:foo,bar,...

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

Integer

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


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

Max:value

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

Mimes:foo,bar,...

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

Basic use of MIME rules

Copy Code code as follows:

' Photo ' => ' mimes:jpeg,bmp,png '

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

Not_in:foo,bar,...

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

Numeric

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

Regex:pattern

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

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

Required

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

Required_if:field,value

When the specified field is a value, the value that verifies the rule must exist.

Required_with:foo,bar,...

The value that verifies this rule must exist only if the specified domain exists.

Required_without:foo,bar,...

The value that verifies this rule must exist only if the specified domain does not exist.

Same:field

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

Size:value

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

Unique:table,column,except,idcolumn

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

Copy Code code as follows:

' Email ' => ' unique:users '
Specify column names
' Email ' => ' unique:users,email_address '
Force to ignore a given ID
' Email ' => ' unique:users,email_address,10 '

Url

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

customizing error messages

If necessary, you can use a custom error message instead of the default message. Here are several ways to customize error messages.

Deliver custom messages to validators

Copy Code code as follows:

$messages = Array (
' Required ' => ' the:attribute field is required. ',
);
$validator = Validator::make ($input, $rules, $messages);

Note: attribute placeholders will be replaced by the names of the fields that are actually validated, and you can use other placeholders in the error message.

Other validation placeholders

Copy Code code as follows:

$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 is one of the following types:
: Values ',
);

Sometimes, you may want to specify a custom error message only for a specified field:

Specifies a custom error message for a specified field

Copy Code code as follows:

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

In some cases, you might want to specify an error message in a language file instead of passing it directly to Validator. To do this, add your custom message to the custom array in the app/lang/xx/validation.php file.

Specify an error message in the language file

Copy Code code as follows:

' Custom ' => array (
' Email ' => Array (
' Required ' => ' We need to know your e-mail address! ',
),
),

Custom validation Rules

Laravel provides a series of useful validation rules, but you may want to add your own validation rules. One way to do this is to use the Validator::extend function to register a custom validation rule:

Sign up for a custom validation rule

Copy Code code as follows:

Validator::extend (' foo ', function ($attribute, $value, $parameters)
{
return $value = = ' Foo ';
});

Note: The name of the rule passed to the extend function must conform to the "snake cased" naming convention.

The custom validator accepts three parameters: the name of the property to be validated, the value of the property to be validated, and the arguments passed to the rule.

You can also pass a function of a class to the extend function, rather than using a closure:

Copy Code code as follows:

Validator::extend (' foo ', ' foovalidator@validate ');

Note that you need to define error messages for your custom rules. You can use either an array of custom messages in one row, or you can add them in the validation language file.

You can also extend the Validator class itself, rather than using the closure callback extension validator. To accomplish this, add a validator class that inherits from the Illuminate\validation\validator. You can add validation functions that start with validate in the class:

Extended Validator Classes

Copy Code code as follows:

<?php
Class CustomValidator extends Illuminate\validation\validator {
Public Function Validatefoo ($attribute, $value, $parameters)
{
return $value = = ' Foo ';
}
}

Below, you need to register a custom validator extension:

You need to register a custom validator extension

Copy Code code as follows:

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

When creating a custom validation rule, you sometimes need to define a custom placeholder for the error message. To implement it, you can create a custom validator like the one above, and add a replacexxx function to the validator:

Copy Code code as follows:

protected function Replacefoo ($message, $attribute, $rule, $parameters)
{
Return Str_replace (': foo ', $parameters [0], $message);
}

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.