PHP – Laravel form validation (validation rules and use of $this->validate(), Validator::make(), Requests)…

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 must perform 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 to value. For strings, value is the number of characters. | |min:value|The field value must be greater than or equal to value. For strings, value is the number of characters. | |email|Verify whether the email is legal. | |url|Validation fields must be in valid URL format. | |confirmed| Verify that the two fields are the same. If the field being verified is password, a matching passward_confirmation field must be entered. | |integer|The validation field must be of integer type. | |ip|The validation field must be an IP address. | |numeric|Validation fields must be numeric. | |size:value|value The validation field must have a size that matches the given value value; 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 specified min and max, a string value or File size is calculated in the same way as the size 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 the UserController 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 page

    Add 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 --}}

    @csrf {{-- Use old('account') When the page is reset, the field will continue to use the old value submitted last time Display, will not be cleared--}}

    User account: < /div>

    User password:
    Confirm password:

    < div>User email:

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

    image.png

    image.png

3. Validator::make() (Independent Verification)
  • Still the case code above, now it needs to be verified through independent 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 through validator

  • Create a validator (custom Request class)

    $ php artisan make:request UserRequest

    There will be an additional Requests folder in the Http folder, which will store all validators. Now it contains the newly created custom Request Class UserRequest

    image.png

  • UserRequest.php: Write validation rules into the UserRequest 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 the UserRequest 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.