Laravel hướng dẫn cách sử dụng Validation với ví dụ cụ thể

04/01/2022   Laravel

Laravel hướng dẫn cách sử dụng Validation với ví dụ cụ thể

Validation dùng để: kiểm tra dữ liệu gửi lên từ phía người dùng có thỏa mãn điều kiện chúng ta đặt ra trước hay không. Nếu dữ liệu gửi lên thỏa điều kiện thì ta thực hiện các thao tác kế tiếp như lưu trữ vào cơ sở dữ liệu, hiển thị dữ liệu.. cho người dùng. Vd về điều kiện như tên phải >=3 và <=30 ký tự, email phải đúng định dạng.

Nội dung 

1. Ví dụ về sử dụng Validation trong Laravel

2. Các validation Hay dùng trong Laravel 


1. Ví dụ về sử dụng Validation trong Laravel: Tạo form thêm Post và kiểm tra dữ liệu gửi lên, nếu có lỗi sẽ thông báo lỗi cho người dùng.

file: \routes\web.php

…..

Route::resources([ 'post' => 'PostController' ]);

…...

file: \app\Http\Controllers\PostController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;

class PostController extends Controller
{
 
    public function create()
    {
        //
        $data['title']='Create Post';
        return view('post.create',['data'=>$data]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {

        //
        $validator = Validator::make($request->all(), 
            [
                'title' => 'required|min:3|max:255',
                'body' => 'required',
            ],
            [
                'required' => ':attribute Không được để trống',
                'min' => ':attribute Không được nhỏ hơn :min',
                'max' => ':attribute Không được lớn hơn :max',
            ],
            [
                'title' => 'Tiêu đề',
                'body' => 'Nội dung',
            ]
        );

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

        // Store the blog post...
        echo 'Dữ liệu hợp lệ có thể lưu vào DB';
    }
}

file: \resources\views\post\create.blade.php

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">{{ __('Create Post') }}</div>

                <div class="card-body">
                    <form method="POST" action="{{ route('post.store') }}">
                        @csrf

                        <div class="form-group row">
                            <label for="title" class="col-md-4 col-form-label text-md-right">{{ __('Title') }}</label>

                            <div class="col-md-6">
                                <input id="title" type="text" class="form-control @error('title') is-invalid @enderror" name="title" value="{{ old('title') }}"   autocomplete="title" autofocus>

                                @error('title')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>
                        </div>

                        <div class="form-group row">
                            <label for="body" class="col-md-4 col-form-label text-md-right">{{ __('body') }}</label>

                            <div class="col-md-6">
                                <input id="body" type="text" class="form-control @error('body') is-invalid @enderror" name="body" value="{{ old('body') }}"  autocomplete="body">

                                @error('body')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>
                        </div>


                        <div class="form-group row mb-0">
                            <div class="col-md-6 offset-md-4">
                                <button type="submit" class="btn btn-primary">
                                    {{ __('Save') }}
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection
 

Để xuất lỗi ra có thể làm theo các cách

Cách 1: xuất ra hết một lần phía trên form

@if(count($errors) > 0)
    @foreach($errors->all() as $err)
    <div class="alert alert-danger">{{$err}}</div>
    @endforeach
@endif

Cách 2: xuất từng lỗi ngay phía dưới input vi dụ với input title

@if ($errors->has('title'))
        <span class="invalid-feedback" role="alert">
            <strong>{{ $errors->first('title') }}</strong>
        </span>
    @endif

Hoặc có thể code theo cách này

@error('title')
    <span class="invalid-feedback" role="alert">
        <strong>{{ $message }}</strong>
    </span>
@enderror

2. Các validation Hay dùng trong Laravel

Rules

Chú Thích

Required

Không được để trống ô dữ liệu.

Boolean

Chỉ cho phép nhập vào các giá trị 0,1,true,false,'0','1' .

confirmed

Kiểm tra 2 input có trùng nhau không, input sau bắt buộc phải có tiền tố _confirmation. VD: password,password_confirmation.

dimensions

 -Giới hạn chiều rộng chiều cao của ảnh. VD: 'avatar' => 'dimensions:min_width=100,min_height=200'

- Các thông số khác: min_widthmax_widthmin_heightmax_heightwidthheightratio.

email

-Dữ liệu nhập vào phải là email.

file

-Dữ liệu nhập vào phải là file.

image

-Dữ liệu nhập vào phải là file ảnh(jpeg, png, bmp, gif, or svg).

in:foo,bar,..

-Dữ liệu nhập vào phải nằm trong list.

integer

-Dữ liệu nhập vào phải là số nguyên.

json

-Dữ liệu nhập vào phải là json

max:value

-Độ dài lớn nhất của dữ liệu nhập vào. VD: max:255.

min:value

-Độ dài nhỏ nhất của dữ liệu nhập vào. VD: min:5.

mimetypes:text/pain,...

-Kiểu dữ liệu của file phải nằm trong list.

VD: 'video' => 'mimetypes:video/avi,video/mpeg,video/quicktime'

numeric

-Dữ liệu nhập vào pải là số.

unique:table

-Dữ liệu nhập vào phải là duy nhất trong bảng.

VD: 'username'=>'unique:users'.

Bài viết cùng chủ đề