Home >Backend Development >PHP Tutorial >Detailed explanation of Laravel framework form validation, laravel framework form_PHP tutorial

Detailed explanation of Laravel framework form validation, laravel framework form_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:19:24704browse

Detailed explanation of Laravel framework form verification, laravel framework form

Basic verification example

Copy code The code is 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 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 single element of an array.

Specify validation rules via array

Copy code The code is 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 code The code is as follows:

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

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

$messages = $validator->messages();

You can also use the failed function to get an array of rules that failed validation without an error message.
Copy code The code is as follows:

$failed = $validator->failed();

Document Verification

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

Copy code The code is as follows:

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

Get all error messages for a domain

Copy code The code is as follows:

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

Get all error messages for all domains

Copy code The code is as follows:

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

Check if messages exist for a domain

Copy code The code is as follows:

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

Get an error message in some format

Copy code The code is as follows:

echo $messages->first('email', '

:message

');

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

Get all error messages in a certain format

Copy code The code is as follows:

​foreach ($messages->all('
  • :message
  • ') as $message)
    {
    //
    }

    Error Messages & Views

    Once you've 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:

    Copy code The code is as follows:

    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 auto-bound $errors variable in the view:

    Copy code The code is as follows:

    first('email'); ?>

    Available validation rules

    Here is a list of all available validation rules and their functions:

    Copy code The code is 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

    Validate that the value of this rule must be yes, on, or 1. This is useful when verifying agreement with the Terms of Service.

    active_url

    Verifies 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
    Validate that the value of 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
    Validates that the value of this rule must be before the given date, which 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
    Validates that the value of this rule must conform to the given format, according to the PHP function date_parse_from_format.

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

    email
    Validate 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 specified database table.

    Basic usage of Exists rules

    Copy code The code is as follows:
    'state' => 'exists:states'

    Specify column name
    Copy code The code is as follows:

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

    You can also specify more conditions, which will be added to the query in the form of "where".
    Copy code The code is as follows:

    '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

    Validate 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

    Validate 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 validating this rule must be in the given list.

    Basic use of MIME rules

    Copy code The code is as follows:

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

    min:value
    The value that validates this rule must be greater than the minimum value. Strings, numbers, and files are compared using size rules.

    not_in:foo,bar,...

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

    numeric

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

    regex:pattern

    Validates that the value of this rule must match the given regular expression.

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

    required

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

    required_if:field,value

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

    required_with:foo,bar,...

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

    required_without:foo,bar,...

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

    same:field

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

    size:value

    Validates that the value of this rule must be the same size as the given value. For strings, value represents the number of characters; for numbers, value represents its integer value; for files, value represents the size of the file in KB.

    unique:table,column,except,idColumn

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

    Basic use of Unique rules

    Copy code The code is as follows:

    'email' => 'unique:users'
    Specify column name
    'email' => 'unique:users,email_address'
    Force ignore a given ID
    'email' => 'unique:users,email_address,10'

    url

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

    Customized error message

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

    Pass custom message to validator

    Copy code The code is as follows:

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

    Note: The :attribute placeholder will be replaced by the name of the actual domain being validated. You can also use other placeholders in the error message.

    Other validation placeholders

    Copy code The code is 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',
    );

    Sometimes, you may want to specify a customized error message only for a specific domain:

    Specify customized error messages for a specific domain

    Copy code The code is as follows:

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

    In some cases, you may want to specify error messages in a language file rather than passing them directly to the Validator. To achieve this, add your custom message to the custom array in the app/lang/xx/validation.php file.

    Specify error message in language file

    Copy code The code is as follows:

    'custom' => array(
    'email' => array(
    'required' => 'We need to know your e-mail address!',
    ),
    ),

    Customized verification rules

    Laravel provides a range of useful validation rules; however, you may wish to add your own. One way is to register custom validation rules using the Validator::extend function:

    Register a custom validation rule

    Copy code The code is as follows:

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

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

    The custom validator accepts three parameters: the name of the attribute to be verified, the value of the attribute to be verified, and the parameters passed to this rule.

    You can also pass a class function to the extend function instead of using a closure:

    Copy code The code is as follows:

    ​Validator::extend('foo', 'FooValidator@validate');

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

     You can also extend the Validator class itself instead of extending the validator with a closure callback. To achieve this, add a validator class that inherits from IlluminateValidationValidator. You can add a validation function starting with validate in the class:

    Extended validator class

    Copy code The code is as follows:

    class CustomValidator extends IlluminateValidationValidator {
    public function validateFoo($attribute, $value, $parameters)
    {
    return $value == 'foo';
    }
    }

    Next, you need to register your custom validator extension:

    You need to register a custom validator extension

    Copy code The code is 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 achieve this, you can create a custom validator like above and add a replaceXXX function in the validator:

    Copy code The code is as follows:

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


    How to call multiple form validation functions in JavaScript?

    You can write a special summary of methods.
    For example:


    function checkFrom(){
    return method1()&&method2()&&method3()&&method4()&&method5 ()..;
    }
    However, it is best to sort out the verification methods and create a more general verification framework.

    Recommend a js form validation framework

    In fact, jqueryValidate can customize error messages. Please refer to its documentation.
    You can use the showErrors attribute here:
    $(".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 message, and the floating box can be controlled using CSS.

    www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/874636.htmlTechArticleLaravel framework form validation detailed explanation, laravel framework form basic validation example copy code code as follows: $validator = Validator::make (array('name' = 'Dayle'), array('name' = 'required|...
    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
    Previous article:Yii Regarding the method of find findAll to find the specified fields, yiifindall_PHP tutorialNext article:Yii Regarding the method of find findAll to find the specified fields, yiifindall_PHP tutorial

    Related articles

    See more