Tùy chỉnh Validation Rules trong Laravel 9
Trong bài viết này, chúng ta sẽ khám phá cách tạo Rules tùy chỉnh trong Laravel 9. Chúng ta sẽ làm theo các bước sau :
-
Tạo ứng dụng laravel 9
-
Tạo Rule ,Controller,Request Form
-
Tạo view và router
-
Chạy chương trình
1 Tạo ứng dụng laravel 9
Tạo app với lệnh sau :
composer create-project laravel/laravel larule
2 Tạo Rule ,Controller,Request Form
Tạo rule với lệnh sau :
php artisan make:rule Phone
Code Rule ở file app/Rules/Phone.php như sau :
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
class Phone implements Rule
{
/**
* Create a new rule instance.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value)
{
$result = preg_match( '/^(0|\+84)(\s|\.)?((3[2-9])|(5[689])|(7[06-9])|(8[1-689])|(9[0-46-9]))(\d)(\s|\.)?(\d{3})(\s|\.)?(\d{3})$/', $value );
if($result)
{
return true;
}
else
{
return false;
}
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return 'Số điện thoại không hợp lệ';
}
}
Sau đó chúng ta dùng lệnh sau :
php artisan make:model Form --all
Lệnh này laravel sẽ tự động tạo các file cần thiết cho ta bao gồm cả Controller ,Request ...
Ở file StoreRequest app/Http/Requests/StoreFormRequest.php
namespace App\Http\Requests;
use App\Rules\Phone;
use Illuminate\Foundation\Http\FormRequest;
class StoreFormRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, mixed>
*/
public function rules()
{
return [
'phone'=>['required','digits:10',new Phone()],
];
}
}
File Controller : app/Http/Controllers/FormController.php
namespace App\Http\Controllers;
use App\Models\Form;
use App\Http\Requests\StoreFormRequest;
use App\Http\Requests\UpdateFormRequest;
class FormController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
return view('form');
}
/**
* Store a newly created resource in storage.
*
* @param \App\Http\Requests\StoreFormRequest $request
* @return \Illuminate\Http\Response
*/
public function store(StoreFormRequest $request)
{
dd($request);
}
}
3 Tạo view và router
Tiếp theo chúng ta sẽ tạo 1 view hiển thị lỗi cũng như form nhập dữ liệu đầu vào resources/views/form.blade.php
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
@if($errors->any())
<div class="alert alert-success" role="alert">
@foreach($errors->all() as $error)
{{ $error }}
@endforeach
</div>
@endif
<div class="main">
<form action="{{route('form.store')}}" method="post">
@csrf
<div class="form-group">
<label for="phone">Số điện thoại</label>
<input type="text" class="form-control" name="phone" id="phone" placeholder="Số điện thoại" value="{{ old('phone') }}">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
Để chương trình có thể chạy được chúng ta thêm router cho controller này ở file routes/web.php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::resource('form',\App\Http\Controllers\FormController::class);
Route::get('/', function () {
return view('welcome');
});
4 ;Chạy chương trình
Để chạy chương trình chúng ta dùng lệnh sau :
php artisan serve
Tiếp dó truy cập link http://127.0.0.1:8000/form
File source code bạn có thể download cuối bài để tham khảo .Chi tiết code ở video
Nếu hay hãy chia sẻ hộ mình .Thanks