Laravel5 series tutorial 7: Form Validation

Source: Internet
Author: User
Laravel5 series tutorial 7: Form Validation

From: https://laravist.com/article/15

Laravist is the Laravel community I just launched. if you have any questions related to Laravel, please come here and ask me. I will try my best to solve the problem. later I will try to record some video tutorials, this is probably the form

Https://laravist.com/lesson/1

I finally want to update the seventh part of this Laravel series of tutorials. I wrote something else.

Let's not talk nonsense. go directly to the Form Validation section. Almost every web application has a form, which is basically inseparable from form verification. In laravel, there are two ways to perform form verification: Request and Validation. The following sections describe these two parts separately, and I will focus more on the first type. We also recommend that you use the first type for form verification:

Request form verification

Why does it focus on explaining the first verification method? I personally think that the first method is easier to maintain and code reuse under the same verification conditions. The code writing method is more suitable for Laravel and my personal habits: you can use command lines to generate code. That is, you can use the artisan tool:

php artisan make:request StoreArticleRequest

Use the make: request command of artisan in the project directory to generate a Request class for form verification. this class is named StoreArticleRequest here, you can also name the name as you like, but I recommend that you make the name more user-friendly when naming it, this will be a lot of benefit for later looking at the code. The file generated by this command is located in the app/Http/Requests/Folder. open this file to see:

class StoreArticleRequest extends Request{    /**     * Determine if the user is authorized to make this request.     *     * @return bool     */    public function authorize()    {        return false;    }    /**     * Get the validation rules that apply to the request.     *     * @return array     */    public function rules()    {        return [            //        ];    }}
Implementation Verification

There are two methods: authorize () and rules (). Authorize () can easily understand whether identity authentication is required when processing this form request (usually a post request). This authentication means: for example, B can edit A comment published by. If not, false is returned. if not, true is returned. The logic here is: since an article is published, users registered on our site (if it is open for registration) can post an article, so we should first modify the authorize () method, change the return value to: return true ;.

Then, for the rules () method, we need to set our verification rules here. For example, we can set the following verification rules:

public function rules()    {        return [            'title' => 'required',            'content' => 'required'        ];    }

Because when we create an article, we have two submitted fields: title and content. This is the two fields we set when designing the articles table.

Then, the verification rules above are as follows: for the title and content fields, we need the user to fill in the content for them. the content cannot be blank.

Since the rules here are set, how can we apply them? That is, how can we verify before saving the article to the database? We only need to slightly modify the ArticleController's store () method:

Public function store (Requests \ StoreArticleRequest $ request) {$ input = $ request-> all (); // add two rows below. Take a look at the Request :: use $ input ['Intro'] = mb_substr ($ request-> get ('content'),) for get );}

We pass the instance of the entire StoreArticleRequest class into the store () method with the $ request variable. at this time, laravel
The system automatically checks whether form verification is required (whether the rules method defines verification rules). If verification is required, laravel first verifies the process. if the verification fails, the code in the store () method will not be executed, but will jump directly to the page that submits the form, which is: http://blog.dev/article/create this page. If all the verifications are passed, the internal store () code will be executed, that is, the code will be executed to $ input = $ request-> all (); here and the code below... For example, let's try to leave it blank:

Feedback error

The image above does not seem to have changed, but it has already been submitted once, but it jumps back immediately. We can verify it using the following method:

@if($errors->any())        
 
 
    @foreach($errors->all() as $error)
  • {{ $error }}
  • @endforeach
@endif

Add the following code to the create. blade. php view file. I will put it here {!! Form: close ()!!} . The meaning here is probably that if there is any form verification error message, we will print this information to the user. If no, no information is displayed. Let's try again:

At this time, we can see that when the form verification fails, the corresponding error message is displayed on the page. If there are no errors, create an article.

Tips: If you do not want the error message to be in English, you can modify it in resources/lang/en/validation. php, or create a new language file package.

Multiple verification rules

OK. here, we basically pass this verification process. However, in actual development, verification is not always simple: what if we want to set multiple verification rules for a field? For example, we want the title of an article to be at least three bytes in length? In this way, in the rules () method:

'title' => 'required|min:3',

In laravel, we use | to separate multiple rules: indicates the value of the rule. In fact, you can also use arrays here, but I recommend that you write them like above, which is concise and clear.

Other common verification rules

As for more verification rules, such as when registering, verifying an email and confirming a password, how can we write it?

'email'=>'required|email','password'=>'required|min:6|confirmed','password_confirmation' => 'required|min:6'

In the above two common scenarios, the most common method is to verify whether the entered information is in the correct email format. As for the password, use confirmed to specify it, note that confirmed is not confirme. In addition, the second password field needs to be written in the form of password_confirmation, that is, in the view, we will have an input form similar to this:

 

For more verification rules, refer to the official documentation:

Http://laravel.com/docs/5.1/validation

Use Validation

Before using this function, you can remove the variables in store (Requests \ StoreArticleRequest $ request ).

Validation is mostly used to verify some simple forms. The demo is written directly in ArticleController and uses Validator: make () directly. the usage is Validator: make (array $ request, array $ rules ), for example, our example can be written in store () as follows:

$input = Request::all();$validator = Validator::make($input, [    'title' => 'required|min:3',    'body' => 'required',]);   

Then you can use the following method to check whether the verification has passed:

 if ($validator->fails())  {            }

After the verification is passed, we proceed to the next step, for example, saving the data to the database. A basic Validation process is complete, and I just want to introduce it here, because I will use the first method: Request.

Tips: both methods use the same verification mechanism.

Summary

Here we have basically finished the basic form verification. in the next section, I will talk about the use of queryScope and SetAttributes. These two are very helpful for Data Warehouse preprocessing and code reuse, so we will talk about these two points next time: we will first set and use the published_at field, and then you will know the benefits of setting this field.

Finally:Happy Hacking

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.