2025年11月30日 星期日

Laravel 12 表單驗證教學

相關系列文章:
01.在 windows 10 安裝 laravel 12 studentManagement環境與設定
02.laravel 12 route 路由
03.laravel 12 Blade Templates 網頁模版
04.laravel 12 Controller 控制器 
05.Laravel 12 Migration 遷移-資料庫版本控制
06.Laravel 12 Model 資料庫中的資料表,並提供與資料庫互動的介面
07.laravel 資料庫資料填充工廠入門
08.laravel 12 Eloquent ORM-Query Builder
09.laravel 12 Eloquent ORM-Eloquent ORM
10.Laravel 12:Eloquent 必學技巧一次掌握(Scopes、Soft Deletes、CRUD)
11.Laravel 12 表單驗證教學
12.Laravel 12 圖片上傳與刪除記錄及文件
13.Laravel 12 Eloquent 關聯完整指南:從基礎到進階的全方位教學

Laravel 12 表單驗證教學包含兩個子項目,分別是
1.Laravel 12 表單驗證教學|用正確方式驗證使用者輸入
2.Laravel 12 的 Form Request 驗證|乾淨且組織化的驗證方式

以下為各分項的詳細內容:

1.Laravel 12 表單驗證教學|用正確方式驗證使用者輸入
在\resources\views\students\add.blade.php 去除 required
@extends('layouts.app')
@section('head')
    <title>Add Students</title>
@endsection

@section('content')
    <section>
        <div class="card shadow-lg">
            <div class="card-header bg-primary text-white">
                <h5 class="mb-0">Student Registration</h5>
            </div>
            <div class="card-body">
                <form action="{{ URL('student/create') }}" method="POST">
                    @csrf
                    <div class="mb-3">
                        <label for="name" class="form-label">Name</label>
                        <input type="text" class="form-control" id="name" name="name">
                    </div>
                    <div class="mb-3">
                        <label for="email" class="form-label">Email</label>
                        <input type="email" class="form-control" id="email" name="email">
                    </div>
                    <div class="mb-3">
                        <label for="age" class="form-label">Age</label>
                        <input type="number" class="form-control" id="age" name="age">
                    </div>
                    <div class="mb-3">
                        <label for="age" class="form-label">Date of Birth</label>
                        <input type="date" class="form-control" id="date_of_birth" name="date_of_birth">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Gender</label>
                        <div>
                            <div class="form-check form-check-inline">
                                <input class="form-check-input" type="radio" name="gender" id="male" value="m" >
                                <label class="form-check-label" for="male">Male</label>
                            </div>
                            <div class="form-check form-check-inline">
                                <input class="form-check-input" type="radio" name="gender" id="female" value="f">
                                <label class="form-check-label" for="female">Female</label>
                            </div>
                        </div>
                    </div>
                    <button type="submit" class="btn btn-success">送出</button>
                </form>
            </div>
        </div>
    </section>
@endsection

在http://127.0.0.1:8000/student/add,什麼資料都不填,直接按下[送出]
就會看到
我們需要在後端作驗證:
在\app\Http\Controllers\StudentController.php 編輯
        $request->validate([
            'name'  => 'required|string|max:255',
            'email' => 'required|email|unique:students,email',
            'age'   => 'required|integer|min:1|max:100',
            'date_of_birth' => 'required|date',
            'gender' => 'required|in:m,f',    
        ]);
如下圖:

為了能夠顯示錯誤訊息,所以我們在\resources\views\students\add.blade.php 編輯如下:
    @if ($errors->any())
        <div class="alert alert-danger">
            <ul>
                @foreach($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif

如下圖:
在http://127.0.0.1:8000/student/add,什麼資料都不填,直接按下[送出]
亦可以自訂錯誤訊息。
在\app\Http\Controllers\StudentController.php 編輯
        $request->validate([
            'name'  => 'required|string|max:255',
            'email' => 'required|email|unique:students,email',
            'age'   => 'required|integer|min:1|max:100',
            'date_of_birth' => 'required|date',
            'gender' => 'required|in:m,f',
        ],[
           'name.required'  => 'Please Write Student Name',
           'age.max' => 'Student can not be older than 100.',
        ]);
如下圖所示:
在http://127.0.0.1:8000/student/add,年紀改填,直接按下[送出]
就可以看到

2.Laravel 12 的 Form Request 驗證|乾淨且組織化的驗證方式
如果將驗證通通寫在Controller ,則Controller 將會異常肥大,管理起來也不方便。因此,將驗證功能移到另一個功能request。

指令:php artisan make:request StudentAddRequest

則會在app\Http\Request\新增一個StudentAddRequest.php
如何讓app\Http\Request\StudentAddRequest.php 可以執行?
    public function authorize(): bool
    {
        return true;
    }

如下圖:
在\app\Http\Controllers\StudentController.php 的設定,重新調整寫入至\app\Http\Request\StudentAddRequest.php
    public function rules(): array
    {
        return [
            //
            'name'  => 'required|string|max:255',
            'email' => 'required|email|unique:students,email',
            'age'   => 'required|integer|min:1|max:100',
            'date_of_birth' => 'required|date',
            'gender' => 'required|in:m,f',
        ];
    }

    public function messages()
    {
        return [
           'name.required'  => 'Please Write Student Name',
           'age.max' => 'Student can not be older than 100.',
        ];
    }

如下圖:
那要如何加入
\app\Http\Controllers\StudentController.php
原先的
  public function create(Request $request) {
要改為
    public function create(StudentAddRequest $request) {
如下圖:
在http://127.0.0.1:8000/student/add,年紀改填,直接按下[送出]
就可以看到
此時,原先的錯誤資料都會被清空。那我要如何保留原先的資料,進行修改?
\resources\views\students\add.blade.php 編輯如下:
value="{{ old('name') }}"
value="{{ old('email') }}"
value="{{ old('age') }}"
value={{ old('date_of_birth') }}
value="m" {{ old('gender')== 'm' ? 'checked':'' }}
value="f" {{ old('gender')== 'f' ? 'checked':'' }}

如下圖:

在http://127.0.0.1:8000/student/add,填入資料,只有age為200,按下submit。就會得到
就會看到,舊的值都會被保留下來
                                          


資料來源:
1.Laravel 12 Form Validation Tutorial | Validate User Input the Right Way
2.Laravel 12 Form Request Validation | Clean & Organized Validation in Laravel
3.11 adding old value


沒有留言:

張貼留言

資科教室更新案ACER 4690G主機,使用網路衛士還原系統。突發故障,無法進入Windows 11,該如何處理?

一、狀況描述:開機後,會直接進入BIOS。一直無法進入Windows 11 的畫面。 處理方式:檢查BIOS設定 1.進入BIOS,按下F1 2.檢查 Security -> Secure Boot-> Disable 與 Chassis Opened Warning...