Học Laravel – Bài 23: Validation (P2)

Custom message trong language file:

Laravel validation error nằm trong file lang/en/validation.php. Nếu app chưa có, sử dụng lệnh php artisan lang:publish để tạo. Bạn có thể thay đổi nội dung file, hoặc copy ra 1 thư mục ngôn ngữ khác (ví dụ vi) để dịch.

Các rule có sẵn trong Laravel:

Xem tại docs: https://laravel.com/docs/10.x/validation#available-validation-rules

  • accepted: field validate phải là "yes", "on", 1 hoặc true. Sử dụng trong trường hợp validate “Term of service”.
  • accepted_if:anotherfield,value,…: field phải là "yes", "on", 1 hoặc true nếu field kia = 1 giá trị cho trước.
  • active_url: field validate phải có record hợp lệ A hoặc AAA theo như dns_get_record function PHP.
  • after:date: Field phải là 1 giá trị sau 1 ngày cho trước. Data sẽ được pass vào strtotime để convert thành 1 instance DateTime hợp lệ:
'start_date' => 'required|date|after:tomorrow',
'finish_date' => 'required|date|after:start_date'
  • after_or_equal:date:
  • alpha: field trong Unicode alphabetic. Để giới hạn trong a-zA-Z sử dụng rule alpha:ascii.
  • alpha_dash: ký tự Unicode alpha-numberic bao gồm dấu -_. Có thể truyền vào alpha_dash:ascii.
  • confirmed: field phải có 1 field khớp của {field}_confirmation. Ví dụ field validate là password, field password_confirmation phải khớp.
  • current_password: input phải khớp với pass hiện tại của user.
  • dimensions: 'avatar' => 'dimensions:min_width=100,min_height=200'
  • exists:table,column: field validate phải tồn tại trong 1 database table cho trước.

Cách dùng exists rule:

'state' => 'exists:states'

Tùy chọn column có thể không cần, field name sẽ được sử dụng. Trong ví dụ này table states có chứa 1 record với 1 giá trị column state khớp với giá trị thuộc tính state của request.

Chỉ định 1 column: bạn có thể chỉ định tên column bằng cách đặt sau tên table:

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

Thi thoảng bạn cần chỉ định 1 database connection:

'email' => 'exists:connection.staff,email'

Bạn cũng có thể chỉ định Eloquent model thay cho table name:

'user_id' => 'exists:App\Models\User,id'

Nếu bạn muốn customize query được thực thi bởi validation rule, bạn có thể sử dụng Rule class:

Validator::make($data, [
    'email' => [
        'required',
        Rule::exists('staff')->where(function (Builder $query) {
            return $query->where('account_id', 1);
        }),
    ],
]);

Dùng Rule::exists:

'state' => Rule::exists('states', 'abbreviation'),
  • Unique:
'email' => 'unique:table_name,column_name'

Validate file:

use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rules\File;
 
Validator::validate($input, [
    'attachment' => [
        'required',
        File::types(['mp3', 'wav'])
            ->min(1024)
            ->max(12 * 1024),
    ],
]);

File image:

use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Rules\File;
 
Validator::validate($input, [
    'photo' => [
        'required',
        File::image()
            ->min(1024)
            ->max(12 * 1024)
            ->dimensions(Rule::dimensions()->maxWidth(1000)->maxHeight(500)),
    ],
]);

// File size:
File::image()
    ->min('1kb')
    ->max('10mb')

Validate password:

use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rules\Password;
 
$validator = Validator::make($request->all(), [
    'password' => ['required', 'confirmed', Password::min(8)],
]);

Có thể mix như sau:

// Require at least 8 characters...
Password::min(8)
 
// Require at least one letter...
Password::min(8)->letters()
 
// Require at least one uppercase and one lowercase letter...
Password::min(8)->mixedCase()
 
// Require at least one number...
Password::min(8)->numbers()
 
// Require at least one symbol...
Password::min(8)->symbols()

Kiểm tra password có bị rò rỉ:

Password::min(8)->uncompromised()

Thiết lập password rule mặc định:

Sử dụng Password::defaults với tham số là closure, closure này trả về config mặc định cho password. Default rule được gọi trong boot method của service provider:

use Illuminate\Validation\Rules\Password;
 
/**
 * Bootstrap any application services.
 */
public function boot(): void
{
    Password::defaults(function () {
        $rule = Password::min(8);
 
        return $this->app->isProduction()
                    ? $rule->mixedCase()->uncompromised()
                    : $rule;
    });
}

Sau đó sử dụng rule như sau:

'password' => ['required', Password::defaults()],

Để lại một bình luận

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *