Laravel framework Form validation in detail, laravel framework Form _php Tutorial

Source: Internet
Author: User
Tags validation examples

Laravel framework Form validation in detail, Laravel framework form


Basic validation Examples

Copy the 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 a "|" character, or as a separate element of an array.

Specifying validation rules by array

Copy the Code code as follows:
$validator = Validator::make (
Array (' name ' = ' Dayle '),
Array (' name ' = = Array (' Required ', ' Min:5 '))
);

Once a Validator instance is created, this validation can be performed using the fails (or passes) function.

Copy the Code code as follows:
if ($validator->fails ())
{
The given data does not pass validation
}
If the validation fails, you can get the error message from the authenticator.
Copy the Code code as follows:
$messages = $validator->messages ();

You can also use the failed function to get an array of rules that do not pass validation without an error message.
Copy the 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 authenticator just like any other validation.

Error message included

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 the Code code as follows:
echo $messages->first (' email ');

Get all error messages for a domain

Copy the Code code as follows:
foreach ($messages->get (' email ') as $message)
{
//
}

Get all error messages for all domains
Copy the Code code as follows:
foreach ($messages->all () as $message)
{
//
}

Check if a domain has a message
Copy the Code code as follows:
if ($messages->has (' email '))
{
//
}

Get an error message in some format

Copy the Code code as follows:
echo $messages->first (' email ', '

: Message

');

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

Get all error messages in some format
Copy the Code code as follows:
foreach ($messages->all ('

  • : Message
  • ') 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 handled conveniently in the lavavel. Take the following route as an example:

    Copy the 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 error message saved in the Session so that it can be made available in the next request.

    However, note that we do not need to explicitly bind the error message to the route in the GET route. 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 conveniently think 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:

    Copy the Code code as follows:
    <?php echo $errors->first (' email ');?>

    Available validation rules

    The following is a list of all the available validation rules and their capabilities:
    Copy the 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)
    Inch
    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 that you agree to the terms of service.

    Active_url

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

    After: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.

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

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

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

    Before:date
    Verify that the value of this rule must precede the given date and the date will pass 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 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 verify this rule is password, so there must be an identical password_confirmation domain in the input.

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

    Date_format:format
    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
    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 legitimate 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 the code as follows: ' state ' = ' exists:states '
    Specify Column Name
    Copy the Code code as follows:
    ' state ' = ' exists:states,abbreviation '

    You can also specify more criteria that will be added to the query in the form of "where."
    Copy the 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 size rules.

    Mimes:foo,bar,...

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

    Base use of MIME rules

    Copy the 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 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 separators, especially when a pipe character is included in a regular expression.

    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, verify that the value of this rule must exist.

    Required_with:foo,bar,...

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

    Required_without:foo,bar,...

    Verify that the value of 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 domain.

    Size:value

    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, 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 the Code code as follows:
    ' Email ' = ' unique:users '
    Specify Column Name
    ' Email ' = ' unique:users,email_address '
    Forces a given ID to be ignored
    ' 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. There are several ways to customize error messages.

    Passing a custom message to the authenticator

    Copy the Code code as follows:
    $messages = Array (
    ' Required ' = ' the:attribute field is required. ',
    );
    $validator = Validator::make ($input, $rules, $messages);

    Note: The attribute placeholder will be replaced with the name of the field that is actually validated, and you can use other placeholders in the error message.

    Additional validation placeholders

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

    In some cases, you may want to specify a custom error message for only one specified domain:

    Specifies a custom error message for a specified domain

    Copy the 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. For this purpose, add your custom message to the custom array in the app/lang/xx/validation.php file.

    To specify an error message in a language file

    Copy the Code code as follows:
    ' Custom ' = = Array (
    ' Email ' = = Array (
    ' Required ' = ' We need to know your e-mail address! ',
    ),
    ),

    Customizing validation rules

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

    Sign up for a custom validation rule
    Copy the 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.

    A 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 instead of using closures:
    Copy the Code code as follows:
    Validator::extend (' foo ', ' foovalidator@validate ');

    Note You need to define the error message for your custom rule. You can either use a custom message array within a line, or you can add it in the validation language file.

    You can also extend the Validator class itself rather than using a closure callback to extend the validator. For this purpose, add an authenticator class that inherits from Illuminate\validation\validator. You can add a validation function that starts with validate in the class:

    Extending the Validator Class
    Copy the 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 the 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 the Code code as follows:
    protected function Replacefoo ($message, $attribute, $rule, $parameters)
    {
    Return Str_replace (': foo ', $parameters [0], $message);
    }


    How does a form-validated function in JavaScript call more than one?

    Can write a method to summarize ah.
    For example:


    function Checkfrom () {
    Return method1 () &&method2 () &&method3 () &&method4 () &&method5 ().
    }
    But it's better to tidy up the validation method and make it a more generic validation framework.

    Recommend a JS form check frame

    In fact, Jqueryvalidate is able to customize the error message. Please refer to its documentation.
    Here you can use the ShowErrors property:
    $ (". Selector"). Validate ({showerrors:function (Errormap, errorlist) {$ ("#summary"). HTML ("Your form contains" + This.numberofinvalids () + "errors, see details below."); This.defaultshowerrors (); }});
    You can also refer to these properties: Errorlabelcontainer,errorcontainer,wrapper,errorelement,validclass,errorclass. You only need to customize the HTML structure of the error hint, and the floating box can be controlled using CSS.


    http://www.bkjia.com/PHPjc/874636.html www.bkjia.com true http://www.bkjia.com/PHPjc/874636.html techarticle Laravel Framework Form Verification in detail, Laravel framework form Basic Verification Example copy code code as follows: $validator = Validator::make (' name ' = ' Dayle '), Array (' name ' = ' r equired| ...

  • 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.