Home > PHP Framework > Laravel > body text

Laravel Development: How to validate form requests using Laravel Validation?

王林
Release: 2023-06-13 13:34:52
Original
1052 people have browsed it

Laravel is a popular PHP web development framework that provides many convenient features to speed up developers' work. Among them, Laravel Validation is a very practical function that can help us easily verify form requests and user-entered data. This article will introduce how to use Laravel Validation to validate form requests.

What is Laravel Validation

Laravel Validation is a form validation method built into the Laravel framework. It provides a concise, standardized, and easy-to-use way to validate form requests and user input data. You can use various rules to verify various data types, reducing code redundancy and simplifying the code development process.

How to use Laravel Validation

First, we need to use Laravel's Validation class in the controller:

use IlluminateSupportFacadesValidator;
Copy after login

When we need to validate a request, we can use Validator: :make() method:

public function store(Request $request)
{
    $validator = Validator::make($request->all(), [
        'name' => 'required|min:3|max:255',
        'email' => 'required|email|unique:users,email',
        'password' => 'required|min:8|confirmed',
    ]);

    if ($validator->fails()) {
        return redirect('register')
                    ->withErrors($validator)
                    ->withInput();
    }

    // 在此处写入数据到数据库的逻辑
}
Copy after login

In the above code, we use the Validator::make() method to define validation rules. The first parameter passed to the make method is the request data that needs to be verified. The second parameter is an array defining validation rules. The keys in the array are the names of fields that need to be validated, and the values ​​are validation rules in the form of strings.

In the above code, we define three fields:

  • name: required, the minimum number of characters is 3, the maximum number of characters is 255
  • email: Required, email format, uniqueness verification
  • password: required, the minimum number of characters is 8, and matches the password_confirmation field

If any rule fails to verify, we will send an error message Return to the registration page and use the withInput() method to return the data previously submitted by the user.

Commonly used validation rules

When using Laravel Validation, there are many rules available. Some common rules are listed below:

  • required: This field must be filled in
  • email: This field must comply with the email address specification
  • unique:table_name, field_name: The value of this field must be unique within the specified data table
  • min:num: The minimum length of this field must be num characters
  • max:num: The maximum length of this field must be It is num characters
  • numeric: The field must be a number
  • integer: The field must be an integer
  • alpha: The field must be a word character (a-z, A-Z)
  • alpha_num: The field must be alphanumeric characters
  • confirmed: The field must match the field value named field_name_confirmation

These rules are only part of the validation rules , you can also use more rules to validate the data. You can find a more detailed list of validation rules in Laravel's documentation.

Custom validation rules

Sometimes, we need custom rules to validate data. In Laravel, we can use the Validator::extend() method to implement custom validation rules. The following is an example of a custom rule:

Validator::extend('phone_number', function ($attribute, $value, $parameters, $validator) {
    return preg_match('/^1[3-9][0-9]{9}$/', $value);
});
Copy after login

In this example, we define a custom rule "phone_number", which will verify whether $formData['phone_number'] meets your own defined specifications. If the verification is successful, return true, otherwise return false.

Customized error message

We can also customize the error message to make the error message more humane. The following is an example of a custom error message:

$validator = Validator::make($request->all(), [
    'email' => 'required|email|unique:users,email',
    'password' => 'required|min:8|confirmed',
]);

// 自定义错误信息
$validator->setAttributeNames([
    'email' => '邮箱',
    'password' => '密码',
]);

// 自定义错误信息模板
$validator->setCustomMessages([
    'required' => ':attribute字段不能为空',
    'email' => '请输入正确的邮箱地址',
    'unique' => ':attribute已经被占用了',
    'min' => ':attribute长度不能小于:min个字符',
    'confirmed' => '密码和确认密码不匹配',
]);
Copy after login

In the above code, we use the setAttributeNames() method to change the field names to make the error message more humane. We also used the setCustomMessages() method to define error message templates to make it easier and faster to change the error message and make it more user-friendly.

Summary

Through the above introduction, we learned how to use Laravel Validation to verify form requests. This can avoid errors caused by incorrect user input, handle error messages more conveniently, and save development time. Laravel Validation can better ensure the robustness and security of applications.

The above is the detailed content of Laravel Development: How to validate form requests using Laravel Validation?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!