1. Introduction
-
Form verification
is to prevent system security problems caused by visitors skipping client verification. Once illegal users bypass client verification without verification on the server, it is very unsafe, so Projects mustperform server-side form validation
. -
Laravel
provides a variety of different validation methods to validate data passed in by the application. -
Commonly used
validation rules
|Rule name|Description| |-|-| |
required
| cannot be empty. | |max:value
|The field value must be less than or equal tovalue
. For strings,value
is the number of characters. | |min:value
|The field value must be greater than or equal tovalue
. For strings,value
is the number of characters. | |email
|Verify whether the email is legal. | |url
|Validation fields must be in validURL
format. | |confirmed
| Verify that the two fields are the same. If the field being verified ispassword
, a matchingpassward_confirmation
field must be entered. | |integer
|The validation field must be of integer type. | |ip
|The validation field must be anIP
address. | |numeric
|Validation fields must be numeric. | |size:value
|value
The validation field must have a size that matches the given valuevalue
; for strings,value
is the corresponding number of characters; for numerical values,value
is the given integer value; for files,value
is the corresponding file word Section number. | |string
|Validation fields must be strings. | |unique
|Table name, field,ID
that needs to be excluded. | |between:min,max
|Verify whether the size of the field value is between the specifiedmin
andmax
, a string value or File size is calculated in the same way as thesize
rule. | |More Validation Rules
|All validation rules available in Laravel and their functions. |
2. $this->validate()
(Case: Form
form to add users)
-
web.php
: User operations are placed in theUserController
file// Add user page Route::get('adduser', 'UserController@index') -> name('user.adduser'); // Add user processing Route::post('adduser', 'UserController @save') -> name('user.adduser');
-
user/index.blade.php
: Display the add user pageAdd new user {{- - If there is an error, it will be prompted and the error message will be output in the template--}} @if($errors->any())- @foreach ($errors->all() as $error)
- {{ $error }}
@endforeach
@endif {{-- Submit to the specified route and obtain the routing address through the alias --}}
-
UserController.php
: User controller page“`
// Display the add user page public function index() { return view(‘user.index’); }//Process the add user operation public function save(Request $request) { // Output request data dump($request->all()); // Before aravel 5.6, the _token verification field was not automatically removed and needed to be removed manually. dump($request->except(['_token'])); //Backend validation of form data //Laravel 5.6 will return an $input, and $input will remove the verification field _token $input = $this->validate($request, [ //Field name => Rule name (multiple rules are separated by |) 'account' => 'required|between:2,6', // The confirmed attribute of the password must be written on the original password 'pwd' => 'required|confirmed', 'pwd_confirmation' => 'required', 'email' => 'required|email' ], [ //Field name.Rule name => Error statement 'account.required' => 'Username cannot be empty', 'account.between' => 'Username must be 2-6 characters', 'pwd.required' => 'Password cannot be empty', 'pwd.confirmed' => 'Two passwords are inconsistent', 'email.required' => 'Email cannot be empty', 'email.email' => 'The email format is incorrect', ]); // Output request data dump($input); }
} “`
-
Demo effect:
3. Validator::make()
(Independent Verification
)
-
Still
the case code above
, now it needs to be verified throughindependent verification
. -
UserController.php
: User controller page“`
// Independent verification, import Validator // use Illuminate\Support\Facades\Validator; // It can be directly abbreviated as follows // Why can it be abbreviated like this? Because there is a configuration in the /config/app.php file to change the path use Validator;
class UserController extends Controller {
// Display the add user page public function index() { return view(‘user.index’); }//Process the add user operation public function save(Request $request) { // Output request data // dump($request->all()); // Before aravel 5.6, the _token verification field was not automatically removed and needed to be removed manually. // dump($request->except(['_token'])); //Backend validation of form data $validate = Validator::make($request->all(), [ //Field name => Rule name (multiple rules are separated by |) 'account' => 'required|between:2,6', // The confirmed attribute of the password must be written on the original password 'pwd' => 'required|confirmed', 'pwd_confirmation' => 'required', 'email' => 'required|email' ], [ //Field name.Rule name => Error statement 'account.required' => 'Username cannot be empty', 'account.between' => 'Username must be 2-6 characters', 'pwd.required' => 'Password cannot be empty', 'pwd_confirmation.required' => 'Confirmation password cannot be empty', 'pwd.confirmed' => 'Two passwords are inconsistent', 'email.required' => 'Email cannot be empty', 'email.email' => 'The email format is incorrect', ]); // Output all available methods of the verification object // dump(get_class_methods($validate)); // Output verification object // dump($validate); // Determine whether verification failed if ($validate->fails()) { //return error result return redirect()->back()->withErrors($validate); } // Output request data dump($request->all()); }
} “`
4. Requests
(Validator
)
-
Still
the case code above
, before it was verified within the current method, now it needs to be verified throughvalidator
-
Create a
validator
(customRequest
class)$ php artisan make:request UserRequest
There will be an additional
Requests
folder in theHttp
folder, which will store all validators. Now it contains the newly created customRequest
ClassUserRequest
-
UserRequest.php
: Write validation rules into theUserRequest
class“`
// Whether to use permission verification, false is used, true is not used, the default is false // return false; return true; }/** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ //Field name => Rule name (multiple rules are separated by |) 'account' => 'required|between:2,6', // The confirmed attribute of the password must be written on the original password 'pwd' => 'required|confirmed', 'pwd_confirmation' => 'required', 'email' => 'required|email' ]; } // Error message public function messages() { return [ //Field name.Rule name => Error statement 'account.required' => 'Username cannot be empty', 'account.between' => 'Username must be 2-6 characters', 'pwd.required' => 'Password cannot be empty', 'pwd_confirmation.required' => 'Confirmation password cannot be empty', 'pwd.confirmed' => 'Two passwords are inconsistent', 'email.required' => 'Email cannot be empty', 'email.email' => 'The email format is incorrect', ]; }
} “`
-
UserController.php
: The user controller page uses theUserRequest
class“`
//Import the custom Request class use App\Http\Requests\UserRequest;
class UserController extends Controller {
// Display the add user page public function index() { return view(‘user.index’); }//Process the add user operation public function save(UserRequest $request) { // Output request data dump($request->all()); // Before aravel 5.6, the _token verification field was not automatically removed and needed to be removed manually. // dump($request->except(['_token'])); //Backend validation of form data // There is no need to write verification here. Replace the above Request with UserRequest to achieve the effect. }
} “`
5. Switch the built-in English error
to Chinese error
- The above are all custom validation errors. If you do not pass custom errors, but switch the default English errors of the system configuration to Chinese, this will be more convenient and simple. You can refer to PHP – Laravel form validation errors to switch to Chinese.