🤩Các rule validation có sẵn (Available validation rules) Phần 3 (ok)

https://viblo.asia/p/tap-21-validation-laravel-tiep-theo-gAm5yGaAZdb

Các rule validation có sẵn (Available validation rules)

Accepted

Trường được xác thực phải có giá trị là "yes", "on", 1 hoặc true. Hữu dụng khi tạo checkbox "Ghi nhớ đăng nhập" hoặc "Đồng ý điều khoản và dịch vụ"...

C:\xampp8\htdocs\plugindev\routes\web.php

<?php
use App\Http\Controllers\PostController;
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::get('/', function () {
  return view('welcome');
});
Route::get('post/create', [PostController::class, 'create']);
Route::post('/post', [PostController::class, 'store']);

C:\xampp8\htdocs\plugindev\app\Http\Controllers\PostController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class PostController extends Controller
{
  /**
   * Display a listing of the resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function index()
  {
    //
  }
  /**
   * Show the form for creating a new resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function create()
  {
    return view('posts.create');
  }
  /**
   * 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(), [
      'remember_me' => 'accepted'
    ]);
    if ($validator->fails()) {
      return response()->json($validator->errors(), 422);
    }
    dd('Done');
  }
}

C:\xampp8\htdocs\plugindev\resources\views\posts\create.blade.php

<style>
  .error {
    color: red;
  }
</style>
<h1>Create new post</h1>
<form action="/post" method="POST">
  @csrf
  <div>
    <p @error('title') class="error" @enderror>
      Title
      @error('title')
      : <span>{{ $message }}</span>
      @enderror
    </p>
    <input type="checkbox" name="remember_me">
  </div>
  <br>
  <div>
    <button type="submit">Create</button>
  </div>
</form>

Active URL

Trường được xác thực phải có bản ghi A hoặc AAAA hợp lệ theo dns_get_record của PHP. Cái này theo mình biết thường dùng để kiểm tra tên miền đã được đăng ký hay chưa, các bạn có thể Google để tìm hiểu thêm. Thường áp dụng cho mấy website thuê tên miền, hosting...

C:\xampp8\htdocs\plugindev\routes\web.php

<?php
use App\Http\Controllers\PostController;
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::get('/', function () {
  return view('welcome');
});
Route::get('post/create', [PostController::class, 'create'])->name('get');
Route::post('/post', [PostController::class, 'store'])->name('post');

C:\xampp8\htdocs\plugindev\app\Http\Controllers\PostController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class PostController extends Controller
{
  /**
   * Display a listing of the resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function index()
  {
    //
  }
  /**
   * Show the form for creating a new resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function create()
  {
    return view('posts.create');
  }
  /**
   * Store a newly created resource in storage.
   *
   * @param  \Illuminate\Http\Request  $request
   * @return \Illuminate\Http\Response
   */
  public function store(Request $request)
  {
    $request->validate([
      'site_active_url' => 'required|active_url'
    ]);
    dd('Done');
  }
}

C:\xampp8\htdocs\plugindev\resources\views\posts\create.blade.php

<!DOCTYPE html>
<html>
<head>
  <title>From</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha512-MoRNloxbStBcD8z3M/2BmnT+rg4IsMxPkXaGh2zD6LGNNFE80W3onsAhRcMAMrSoyWL9xD7Ert0men7vR8LUZg==" crossorigin="anonymous" />
  <scractive_urlt src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></scractive_urlt>
  <scractive_urlt src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></scractive_urlt>
</head>
<body class="bg-dark">
  <div class="container">
    <div class="row">
      <div class="col-md-6 offset-3">
        <div class="card mt-5">
          <div class="card-header">
            <div class="row">
              <div class="col-md-9">
                Laravel Validation active_url Example
              </div>
              <div class="col-md-3 text-right">
                <a href="{{ route('get') }}" class="btn btn-sm btn-outline-primary">Back</a>
              </div>
            </div>
          </div>
          <div class="card-body">
            @if (count($errors) > 0)
            <div class="row">
              <div class="col-md-12">
                <div class="alert alert-danger alert-dismissible">
                  <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
                  @foreach($errors->all() as $error)
                  {{ $error }} <br>
                  @endforeach
                </div>
              </div>
            </div>
            @endif
            <form action="{{ route('post') }}" method="post">
              @csrf
              <div class="row">
                <div class="col-md-12">
                  <div class="form-group">
                    <label>Site URL: No:</label>
                    <input name="site_active_url" type="text" class="form-control">
                  </div>
                </div>
              </div>
              <div class="row">
                <div class="col-md-12">
                  <button class="btn btn-block btn-success">Submit</button>
                </div>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
  </div>
</body>
</html>

Date

Trường được xác thực phải có giá trị là một date hợp lệ, không liên quan theo hàm strtotime của PHP.

C:\xampp8\htdocs\plugindev\routes\web.php

<?php
use App\Http\Controllers\PostController;
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::get('/', function () {
  return view('welcome');
});
Route::get('post/create', [PostController::class, 'create'])->name('get');
Route::post('/post', [PostController::class, 'store'])->name('post');

C:\xampp8\htdocs\plugindev\app\Http\Controllers\PostController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class PostController extends Controller
{
  /**
   * Display a listing of the resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function index()
  {
    //
  }
  /**
   * Show the form for creating a new resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function create()
  {
    return view('posts.create');
  }
  /**
   * Store a newly created resource in storage.
   *
   * @param  \Illuminate\Http\Request  $request
   * @return \Illuminate\Http\Response
   */
  public function store(Request $request)
  {
    $request->validate([
      'date_string' => 'date'
    ]);
    dd('Done');
  }
}

C:\xampp8\htdocs\plugindev\resources\views\posts\create.blade.php

<style>
  .error {
    color: red;
  }
</style>
<h1>Create new post</h1>
<form action="{{ route('post') }}" method="POST">
  @csrf
  <div>
    <p @error('title') class="error" @enderror>
      Title
      @error('title')
      : <span>{{ $message }}</span>
      @enderror
    </p>
    <input type="text" name="date_string">
  </div>
  <br>
  <div>
    <button type="submit">Create</button>
  </div>
</form>

Date format

Trường được xác thực phải phù hợp với định dạng date đã cho. Bạn chỉ nên sử dụng một trong hai rule date hoặc date_format để xác định một trường, không phải cả hai.

C:\xampp8\htdocs\plugindev\app\Http\Controllers\PostController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class PostController extends Controller
{
  /**
   * Display a listing of the resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function index()
  {
    //
  }
  /**
   * Show the form for creating a new resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function create()
  {
    return view('posts.create');
  }
  /**
   * Store a newly created resource in storage.
   *
   * @param  \Illuminate\Http\Request  $request
   * @return \Illuminate\Http\Response
   */
  public function store(Request $request)
  {
    $validator = $request->validate([
      'date_string' => 'date_format:"d/m/Y"'
    ]);
    dd('Done');
  }
}

C:\xampp8\htdocs\plugindev\resources\views\posts\create.blade.php

<style>
  .error {
    color: red;
  }
</style>
<h1>Create new post</h1>
<form action="{{ route('post') }}" method="POST">
  @csrf
  <div>
    <p @error('date_string') class="error" @enderror>
      Title
      @error('date_string')
      : <span>{{ $message }}</span>
      @enderror
    </p>
    <input type="text" name="date_string">
  </div>
  <br>
  <div>
    <button type="submit">Create</button>
  </div>
</form>

Date equals

Trường được xác thực phải có date bằng date đã cho. Date được chuyển vào hàm strtotime của PHP.

C:\xampp8\htdocs\plugindev\app\Http\Controllers\PostController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class PostController extends Controller
{
  /**
   * Display a listing of the resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function index()
  {
    //
  }
  /**
   * Show the form for creating a new resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function create()
  {
    return view('posts.create');
  }
  /**
   * Store a newly created resource in storage.
   *
   * @param  \Illuminate\Http\Request  $request
   * @return \Illuminate\Http\Response
   */
  public function store(Request $request)
  {
    $request->validate([
      'date_string' => 'date_equals:date'
    ]);
    dd('Done');
  }
}

C:\xampp8\htdocs\plugindev\resources\views\posts\create.blade.php

<style>
  .error {
    color: red;
  }
</style>
<h1>Create new post</h1>
<form action="{{ route('post') }}" method="POST">
  @csrf
  <div>
    <p @error('date_string') class="error" @enderror>
      Title
      @error('date_string')
      : <span>{{ $message }}</span>
      @enderror
    </p>
    <input type="text" name="date_string">
    <input type="text" name="date" value="04/05/1987">
  </div>
  <br>
  <div>
    <button type="submit">Create</button>
  </div>
</form>

After (Date)

Trường được xác thực phải có giá trị là date sau date đã cho. Date sẽ được chuyển vào strtotime của PHP.

C:\xampp8\htdocs\plugindev\app\Http\Controllers\PostController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class PostController extends Controller
{
  /**
   * Display a listing of the resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function index()
  {
    //
  }
  /**
   * Show the form for creating a new resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function create()
  {
    return view('posts.create');
  }
  /**
   * Store a newly created resource in storage.
   *
   * @param  \Illuminate\Http\Request  $request
   * @return \Illuminate\Http\Response
   */
  public function store(Request $request)
  {
    $validator = $request->validate([
      'date_string' => 'date_format:"d/m/Y"|after:"10/06/2001"'
    ]);
    dd('Done');
  }
}

C:\xampp8\htdocs\plugindev\resources\views\posts\create.blade.php

<style>
  .error {
    color: red;
  }
</style>
<h1>Create new post</h1>
<form action="{{ route('post') }}" method="POST">
  @csrf
  <div>
    <p @error('date_string') class="error" @enderror>
      Title
      @error('date_string')
      : <span>{{ $message }}</span>
      @enderror
    </p>
    <input type="text" name="date_string">
  </div>
  <br>
  <div>
    <button type="submit">Create</button>
  </div>
</form>

After or equal (Date)

Trường được xác thực phải có giá trị là date sau hoặc bằng date đã cho.

C:\xampp8\htdocs\plugindev\app\Http\Controllers\PostController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class PostController extends Controller
{
  /**
   * Display a listing of the resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function index()
  {
    //
  }
  /**
   * Show the form for creating a new resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function create()
  {
    return view('posts.create');
  }
  /**
   * Store a newly created resource in storage.
   *
   * @param  \Illuminate\Http\Request  $request
   * @return \Illuminate\Http\Response
   */
  public function store(Request $request)
  {
    $validator = $request->validate([
      'date_string' => 'date_format:"d/m/Y"|after_or_equal:"10/06/2001"'
    ]);
    dd('Done');
  }
}

C:\xampp8\htdocs\plugindev\resources\views\posts\create.blade.php

<style>
  .error {
    color: red;
  }
</style>
<h1>Create new post</h1>
<form action="{{ route('post') }}" method="POST">
  @csrf
  <div>
    <p @error('date_string') class="error" @enderror>
      Title
      @error('date_string')
      : <span>{{ $message }}</span>
      @enderror
    </p>
    <input type="text" name="date_string">
  </div>
  <br>
  <div>
    <button type="submit">Create</button>
  </div>
</form>

Alpha

Trường được xác thực chỉ được chứa chữ cái.

C:\xampp8\htdocs\plugindev\app\Http\Controllers\PostController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class PostController extends Controller
{
  /**
   * Display a listing of the resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function index()
  {
    //
  }
  /**
   * Show the form for creating a new resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function create()
  {
    return view('posts.create');
  }
  /**
   * Store a newly created resource in storage.
   *
   * @param  \Illuminate\Http\Request  $request
   * @return \Illuminate\Http\Response
   */
  public function store(Request $request)
  {
    $validator = $request->validate([
      'title' => 'alpha'
    ]);
    dd('Done');
  }
}

C:\xampp8\htdocs\plugindev\resources\views\posts\create.blade.php

<style>
  .error {
    color: red;
  }
</style>
<h1>Create new post</h1>
<form action="{{ route('post') }}" method="POST">
  @csrf
  <div>
    <p @error('title') class="error" @enderror>
      Title
      @error('title')
      : <span>{{ $message }}</span>
      @enderror
    </p>
    <input type="text" name="title">
  </div>
  <br>
  <div>
    <button type="submit">Create</button>
  </div>
</form>

Alpha dash

Trường được xác thực chỉ được chứa chữ cái và số, cũng như dấu -_.

C:\xampp8\htdocs\plugindev\app\Http\Controllers\PostController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class PostController extends Controller
{
  /**
   * Display a listing of the resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function index()
  {
    //
  }
  /**
   * Show the form for creating a new resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function create()
  {
    return view('posts.create');
  }
  /**
   * Store a newly created resource in storage.
   *
   * @param  \Illuminate\Http\Request  $request
   * @return \Illuminate\Http\Response
   */
  public function store(Request $request)
  {
    $validator = $request->validate([
      'title' => 'alpha_dash'
    ]);
    dd('Done');
  }
}

C:\xampp8\htdocs\plugindev\resources\views\posts\create.blade.php

<style>
  .error {
    color: red;
  }
</style>
<h1>Create new post</h1>
<form action="{{ route('post') }}" method="POST">
  @csrf
  <div>
    <p @error('title') class="error" @enderror>
      Title
      @error('title')
      : <span>{{ $message }}</span>
      @enderror
    </p>
    <input type="text" name="title">
  </div>
  <br>
  <div>
    <button type="submit">Create</button>
  </div>
</form>

Alpha numeric

Trường được xác thực chỉ được chứa chữ cái và số.

C:\xampp8\htdocs\plugindev\app\Http\Controllers\PostController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class PostController extends Controller
{
  /**
   * Display a listing of the resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function index()
  {
    //
  }
  /**
   * Show the form for creating a new resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function create()
  {
    return view('posts.create');
  }
  /**
   * Store a newly created resource in storage.
   *
   * @param  \Illuminate\Http\Request  $request
   * @return \Illuminate\Http\Response
   */
  public function store(Request $request)
  {
    $validator = $request->validate([
      'title' => 'alpha_num'
    ]);
    dd('Done');
  }
}

C:\xampp8\htdocs\plugindev\resources\views\posts\create.blade.php

<style>
  .error {
    color: red;
  }
</style>
<h1>Create new post</h1>
<form action="{{ route('post') }}" method="POST">
  @csrf
  <div>
    <p @error('title') class="error" @enderror>
      Title
      @error('title')
      : <span>{{ $message }}</span>
      @enderror
    </p>
    <input type="text" name="title">
  </div>
  <br>
  <div>
    <button type="submit">Create</button>
  </div>
</form>

Numeric

Trường được xác thực phải là một số.

C:\xampp8\htdocs\plugindev\app\Http\Controllers\PostController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class PostController extends Controller
{
  /**
   * Display a listing of the resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function index()
  {
    //
  }
  /**
   * Show the form for creating a new resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function create()
  {
    return view('posts.create');
  }
  /**
   * Store a newly created resource in storage.
   *
   * @param  \Illuminate\Http\Request  $request
   * @return \Illuminate\Http\Response
   */
  public function store(Request $request)
  {
    $request->validate([
      'text' => 'numeric'
    ]);
    dd("done1");
  }
}

C:\xampp8\htdocs\plugindev\resources\views\posts\create.blade.php

<!DOCTYPE html>
<html>
<head>
  <title>Laravel Validation Mimes Foo,Bar,... Example</title>
  <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
  <div class="container">
    <h2>Laravel Validation Mimes Foo,Bar,... Example</h2>
    <form method="POST" action="{{ route('post') }}" autocomplete="off" enctype="multipart/form-data">
      <input type="hidden" name="_token" value="{{ csrf_token() }}">
      @if(count($errors))
      <div class="alert alert-danger">
        <strong>Whoops!</strong> There were some problems with your input.
        <br />
        <ul>
          @foreach($errors->all() as $error)
          <li>{{ $error }}</li>
          @endforeach
        </ul>
      </div>
      @endif
      <div class="row">
        <div class="col-md-12">
          <div class="form-group">
            <input type="text" name="text">
          </div>
        </div>
      </div>
      <div class="form-group">
        <button class="btn btn-success">Submit</button>
      </div>
    </form>
  </div>
</body>
</html>

Digits

Trường được xác thực phải là số và có độ dài bẳng độ dài đã cho.

C:\xampp8\htdocs\plugindev\resources\views\posts\create.blade.php

<style>
  .error {
    color: red;
  }
</style>
<h1>Create new post</h1>
<form action="{{ route('post') }}" method="POST">
  @csrf
  <div>
    <p @error('input1') class="error" @enderror>
      Title
      @error('input1')
      : <span>{{ $message }}</span>
      @enderror
    </p>
    <input type="text" name="numeric">
  </div>
  <br>
  <div>
    <button type="submit">Create</button>
  </div>
</form>

C:\xampp8\htdocs\plugindev\app\Http\Controllers\PostController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class PostController extends Controller
{
  /**
   * Display a listing of the resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function index()
  {
    //
  }
  /**
   * Show the form for creating a new resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function create()
  {
    return view('posts.create');
  }
  /**
   * Store a newly created resource in storage.
   *
   * @param  \Illuminate\Http\Request  $request
   * @return \Illuminate\Http\Response
   */
  public function store(Request $request)
  {
    $request->validate([
      'numeric' => 'digits:3'
    ]);
    dd('Done');
  }
}

Digits between

Trường được xác thực phải là số và có độ dài nằm trong khoảng min, max đã cho.

C:\xampp8\htdocs\plugindev\app\Http\Controllers\PostController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class PostController extends Controller
{
  /**
   * Display a listing of the resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function index()
  {
    //
  }
  /**
   * Show the form for creating a new resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function create()
  {
    return view('posts.create');
  }
  /**
   * Store a newly created resource in storage.
   *
   * @param  \Illuminate\Http\Request  $request
   * @return \Illuminate\Http\Response
   */
  public function store(Request $request)
  {
    $request->validate([
      'numeric' => 'digits_between:3,9'
    ]);
    dd('Done');
  }
}

C:\xampp8\htdocs\plugindev\resources\views\posts\create.blade.php

<style>
  .error {
    color: red;
  }
</style>
<h1>Create new post</h1>
<form action="{{ route('post') }}" method="POST">
  @csrf
  <div>
    <p @error('input1') class="error" @enderror>
      Title
      @error('input1')
      : <span>{{ $message }}</span>
      @enderror
    </p>
    <input type="text" name="numeric">
  </div>
  <br>
  <div>
    <button type="submit">Create</button>
  </div>
</form>

Integer

Trường được xác thực phải là một số nguyên.

Array

Trường được xác thực phải có định dạng mảng PHP.

C:\xampp8\htdocs\plugindev\app\Http\Controllers\PostController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class PostController extends Controller
{
  /**
   * Display a listing of the resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function index()
  {
    //
  }
  /**
   * Show the form for creating a new resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function create()
  {
    return view('posts.create');
  }
  /**
   * Store a newly created resource in storage.
   *
   * @param  \Illuminate\Http\Request  $request
   * @return \Illuminate\Http\Response
   */
  public function store(Request $request)
  {
    $validator = $request->validate([
      "country_name"    => "required|array",
      "country_name.*"  => "required",
    ]);
    dd('Done');
  }
}

C:\xampp8\htdocs\plugindev\resources\views\posts\create.blade.php

<!DOCTYPE html>
<html>
<head>
  <title>Laravel Validation array Example</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
</head>
<body>
  <div class="container">
    <h1>Laravel Validation array Example</h1>
    <div class="card-body">
      @if (count($errors) > 0)
      <div class="row">
        <div class="col-md-12">
          <div class="alert alert-danger alert-dismissible">
            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
            @foreach($errors->all() as $error)
            {{ $error }} <br>
            @endforeach
          </div>
        </div>
      </div>
      @endif
      {!! Form::open(array('route' => 'post','method'=>'POST')) !!}
      <div class="row">
        <div class="col-md-12">
          <div class="form-group">
            <label>Country Name</label>
            {{ Form::text('country_name[]', null ,['class'=>'form-control', 'placeholder'=>'Country Name 1'] ) }}
            {{ Form::text('country_name[]', null ,['class'=>'form-control', 'placeholder'=>'Country Name 2'] ) }}
            {{ Form::text('country_name[]', null ,['class'=>'form-control', 'placeholder'=>'Country Name 3'] ) }}
            @if($errors->has('country_name'))
            <span class="text-danger">{{ $errors->first('country_name') }}</span>
            @endif
          </div>
        </div>
      </div>
      <div class="row">
        <div class="col-md-12 text-center mt-2 mb-3">
          <button type="submit" class="btn btn-success">Submit</button>
        </div>
      </div>
      {!! Form::close() !!}
    </div>
  </div>
</body>
</html>

Distinct

Khi làm việc với array, trường được xác thực không được có gí trị trùng lặp nào.

C:\xampp8\htdocs\plugindev\app\Http\Controllers\PostController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class PostController extends Controller
{
  /**
   * Display a listing of the resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function index()
  {
    //
  }
  /**
   * Show the form for creating a new resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function create()
  {
    return view('posts.create');
  }
  /**
   * Store a newly created resource in storage.
   *
   * @param  \Illuminate\Http\Request  $request
   * @return \Illuminate\Http\Response
   */
  public function store(Request $request)
  {
    $array = [
      ['id' => 1],
      ['id' => 1],
    ];
    $rules = [
      '*.id' => 'distinct',
    ];
    Validator::make($array, $rules)->validate();
    dd('done');
  }
}

Hoặc

C:\xampp8\htdocs\plugindev\app\Http\Controllers\PostController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class PostController extends Controller
{
  /**
   * Display a listing of the resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function index()
  {
    //
  }
  /**
   * Show the form for creating a new resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function create()
  {
    return view('posts.create');
  }
  /**
   * Store a newly created resource in storage.
   *
   * @param  \Illuminate\Http\Request  $request
   * @return \Illuminate\Http\Response
   */
  public function store(Request $request)
  {
    $array = [
      'test' => [
        ['id' => 1],
        ['id' => 1]
      ]
    ];
    $rules = [
      'test.*.id' => 'distinct',
    ];
    Validator::make($array, $rules)->validate();
    dd('done');
  }
}

In

Trường được xác thực phải là một phần tử nằm trong mảng đã cho.

Mặc định:

'item' => 'in:' . implode(',', [1, 2, 3, 4, 5])

Đôi khi sử dụng valiation rule còn khá nhiều hạn chế. Chính vì vậy, ta có thể sử dụng method Rule::in để linh hoạt hơn.

use Illuminate\Validation\Rule;

'item' => [
    'other_rule',
    Rule::in([1, 2, 3, 4, 5])
];

C:\xampp8\htdocs\plugindev\app\Http\Controllers\PostController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class PostController extends Controller
{
  /**
   * Display a listing of the resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function index()
  {
    //
  }
  /**
   * Show the form for creating a new resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function create()
  {
    return view('posts.create');
  }
  /**
   * Store a newly created resource in storage.
   *
   * @param  \Illuminate\Http\Request  $request
   * @return \Illuminate\Http\Response
   */
  public function store(Request $request)
  {
    $request->validate([
      'item' => 'in:' . implode(',', [1, 2, 3, 4, 5])
    ]);
    dd('Done');
  }
}

C:\xampp8\htdocs\plugindev\routes\web.php

<?php
use App\Http\Controllers\PostController;
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::get('/', function () {
  return view('welcome');
});
Route::get('post/create', [PostController::class, 'create'])->name('get');
Route::post('/post', [PostController::class, 'store'])->name('post');

C:\xampp8\htdocs\plugindev\resources\views\posts\create.blade.php

<style>
  .error {
    color: red;
  }
</style>
<h1>Create new post</h1>
<form action="{{ route('post') }}" method="POST">
  @csrf
  <div>
    @foreach ($errors->all() as $error)
    <p class="error">{{ $error }}</p>
    @endforeach
    <input type="text" name="item">
  </div>
  <br>
  <div>
    <button type="submit">Create</button>
  </div>
</form>

In array

Trường được xác thực phải có giá trị thuộc các key của mảng. Thường để kiểm tra một giá trị có tồn tại trong multi-level array hay không.

C:\xampp8\htdocs\plugindev\routes\web.php

<?php
use App\Http\Controllers\PostController;
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::get('/', function () {
  return view('welcome');
});
Route::get('post/create', [PostController::class, 'create'])->name('get');
Route::post('/post', [PostController::class, 'store'])->name('post');

C:\xampp8\htdocs\plugindev\app\Http\Controllers\PostController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class PostController extends Controller
{
  /**
   * Display a listing of the resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function index()
  {
    //
  }
  /**
   * Show the form for creating a new resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function create()
  {
    return view('posts.create');
  }
  /**
   * Store a newly created resource in storage.
   *
   * @param  \Illuminate\Http\Request  $request
   * @return \Illuminate\Http\Response
   */
  public function store(Request $request)
  {
    $request->merge([
      'users' => [
        [
          'id' => 1,
          'username' => 'lechihuy'
        ],
        [
          'id' => 2,
          'username' => 'huydeo'
        ]
      ]
    ]);
    $request->validate([
      'id' => 'in_array:users.*'
    ]);
    dd('Done');
  }
}

C:\xampp8\htdocs\plugindev\resources\views\posts\create.blade.php

<style>
  .error {
    color: red;
  }
</style>
<h1>Create new post</h1>
<form action="{{ route('post') }}" method="POST">
  @csrf
  <div>
    @foreach ($errors->all() as $error)
    <p class="error">{{ $error }}</p>
    @endforeach
    <input type="text" name="id">
  </div>
  <br>
  <div>
    <button type="submit">Create</button>
  </div>
</form>

Not in

Trường được xác thực phải không phải là một phần tử nằm trong mảng đã cho.

Bail

Dừng validation rule input nếu thất bại tại rule trước đó. đỡ phải tốn query :)

Before (Date)

Trường được xác thực phải có giá trị là date trước date đã cho.

C:\xampp8\htdocs\plugindev\app\Http\Controllers\PostController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class PostController extends Controller
{
  /**
   * Display a listing of the resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function index()
  {
    //
  }
  /**
   * Show the form for creating a new resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function create()
  {
    return view('posts.create');
  }
  /**
   * Store a newly created resource in storage.
   *
   * @param  \Illuminate\Http\Request  $request
   * @return \Illuminate\Http\Response
   */
  public function store(Request $request)
  {
    $validator = $request->validate([
      'date_string' => 'before:date'
    ]);
    dd('Done');
  }
}

C:\xampp8\htdocs\plugindev\resources\views\posts\create.blade.php

<style>
  .error {
    color: red;
  }
</style>
<h1>Create new post</h1>
<form action="{{ route('post') }}" method="POST">
  @csrf
  <div>
    <p @error('date_string') class="error" @enderror>
      Title
      @error('date_string')
      : <span>{{ $message }}</span>
      @enderror
    </p>
    <input type="text" name="date_string">
  </div>
  <br>
  <div>
    <button type="submit">Create</button>
  </div>
</form>

Before or equal (Date)

Trường được xác thực phải có giá trị là date trước hoặc bằng date đã cho.

Between

Với chuỗi:

'string' => 'between:5,10'

Với số cần lưu ý một chút, ta cần phải thêm rule number để xác thực là số trước khi rule between được kiểm tra.

'number' => 'numeric|between:5,10'
// Phần tử của mảng từ 2-5 phần tử
'array' => 'between:2,5' 
// Kích thước của file từ 200-1000 KB
'file' => 'between:200,1000' 

Boolean

Trường được xác định phải ở dạng boolean, có thể chấp nhận true, false, 1, 0, "1""0".

C:\xampp8\htdocs\plugindev\app\Http\Controllers\PostController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class PostController extends Controller
{
  /**
   * Display a listing of the resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function index()
  {
    //
  }
  /**
   * Show the form for creating a new resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function create()
  {
    return view('posts.create');
  }
  /**
   * Store a newly created resource in storage.
   *
   * @param  \Illuminate\Http\Request  $request
   * @return \Illuminate\Http\Response
   */
  public function store(Request $request)
  {
    $validator = $request->validate([
      'answer' => 'required|boolean'
    ]);
    dd('Done');
  }
}

C:\xampp8\htdocs\plugindev\resources\views\posts\create.blade.php

<style>
  .error {
    color: red;
  }
</style>
<h1>Create new post</h1>
<form action="{{ route('post') }}" method="POST">
  @csrf
  <div>
    <p @error('answer') class="error" @enderror>
      Title
      @error('answer')
      : <span>{{ $message }}</span>
      @enderror
    </p>
    <input type="radio" value="1" name="answer">
    <input type="radio" value="0" name="answer">
  </div>
  <br>
  <div>
    <button type="submit">Create</button>
  </div>
</form>

Confirmed

Trường foo được xác thực phải khớp với trường foo_confirmation. Chẳng hạn bạn muốn xác thực trường password với rule confirmed, trường password_confirmation phù hợp (khớp với trường password) phải có mặt trong request.

C:\xampp8\htdocs\plugindev\app\Http\Controllers\PostController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class PostController extends Controller
{
  /**
   * Display a listing of the resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function index()
  {
    //
  }
  /**
   * Show the form for creating a new resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function create()
  {
    return view('posts.create');
  }
  /**
   * Store a newly created resource in storage.
   *
   * @param  \Illuminate\Http\Request  $request
   * @return \Illuminate\Http\Response
   */
  public function store(Request $request)
  {
    $validator = $request->validate([
      'password' => 'confirmed'
    ]);
    dd('Done');
  }
}

C:\xampp8\htdocs\plugindev\resources\views\posts\create.blade.php

<style>
  .error {
    color: red;
  }

</style>
<h1>Create new post</h1>
<form action="{{ route('post') }}" method="POST">
  @csrf
  <div>
    <p @error('password') class="error" @enderror>
      Title
      @error('password')
      : <span>{{ $message }}</span>
      @enderror
    </p>
    <input type="text" name="password">
    <input type="text" name="password_confirmation">
  </div>
  <br>
  <div>
    <button type="submit">Create</button>
  </div>
</form>

Different

Trường được xác thực phải có giá trị khác với trường đã cho.

C:\xampp8\htdocs\plugindev\app\Http\Controllers\PostController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class PostController extends Controller
{
  /**
   * Display a listing of the resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function index()
  {
    //
  }
  /**
   * Show the form for creating a new resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function create()
  {
    return view('posts.create');
  }
  /**
   * Store a newly created resource in storage.
   *
   * @param  \Illuminate\Http\Request  $request
   * @return \Illuminate\Http\Response
   */
  public function store(Request $request)
  {
    $request->validate([
      'input1' => 'different:input2'
    ]);
    dd('Done');
  }
}

C:\xampp8\htdocs\plugindev\resources\views\posts\create.blade.php

<style>
  .error {
    color: red;
  }
</style>
<h1>Create new post</h1>
<form action="{{ route('post') }}" method="POST">
  @csrf
  <div>
    <p @error('input1') class="error" @enderror>
      Title
      @error('input1')
      : <span>{{ $message }}</span>
      @enderror
    </p>
    <input type="text" name="input1">
    <input type="text" name="input2">
  </div>
  <br>
  <div>
    <button type="submit">Create</button>
  </div>
</form>

Dimensions

Trường được xác thực phải là một ảnh và đáp ứng các ràng buộc về kích thước được chỉ định bởi các tham số của rule.

Validation rule: Có tất cả 7 loại tham số:

  • min_width

  • min_height

  • max_width

  • max_height

  • ratio: giá trị tỉ lệ = chiều rộng / chiều cao hoặc bằng số float nào đó

  • width

  • height

C:\xampp8\htdocs\plugindev\app\Http\Controllers\PostController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class PostController extends Controller
{
  /**
   * Display a listing of the resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function index()
  {
    //
  }
  /**
   * Show the form for creating a new resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function create()
  {
    return view('posts.create');
  }
  /**
   * Store a newly created resource in storage.
   *
   * @param  \Illuminate\Http\Request  $request
   * @return \Illuminate\Http\Response
   */
  public function store(Request $request)
  {
    // Ensures to the image width and height 
    $this->validate($request, [
      'avatar' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048|dimensions:width=500,height=500',
    ]);
    dd('done');
  }
}

C:\xampp8\htdocs\plugindev\resources\views\posts\create.blade.php

<!DOCTYPE html>
<html>
<head>
  <title>Laravel Validation Dimensions Example</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
</head>
<body>
  <div class="container">
    <h1>Laravel Validation Dimensions Example</h1>
    <div class="card-body">
      @if (count($errors) > 0)
      <div class="row">
        <div class="col-md-12">
          <div class="alert alert-danger alert-dismissible">
            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
            @foreach($errors->all() as $error)
            {{ $error }} <br>
            @endforeach
          </div>
        </div>
      </div>
      @endif
      {!! Form::open(array('route' => 'post','method'=>'POST','enctype'=>'multipart/form-data')) !!}
      <div class="row">
        <div class="col-md-12">
          <div class="form-group">
            <label>avatar</label>
            <input type="file" class="form-control" placeholder="Rejection Reason" name="avatar">
          </div>
        </div>
      </div>
      <div class="row">
        <div class="col-md-12 text-center mt-2 mb-3">
          <button type="submit" class="btn btn-success">Submit</button>
        </div>
      </div>
      {!! Form::close() !!}
    </div>
  </div>
</body>
</html>

Email

Trường được xác thực phải là một địa chỉ email. Trong giới hạn, rule này sử dụng gói egulias/email-vaidator để validate email. Trong đó có các validator như:

  • rfc: RFCValidator

  • strict: NoRFCWarningsValidation

  • spoof: SpoofCheckValidation

  • dns: DNSCheckValidation

  • filter: FilterEmailValidation

Mặc định Laravel sử dụng validator rfc để validate. Với validator filter, nó sử dụng method filter_var để validate.

C:\xampp8\htdocs\plugindev\app\Http\Controllers\PostController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class PostController extends Controller
{
  /**
   * Display a listing of the resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function index()
  {
    //
  }
  /**
   * Show the form for creating a new resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function create()
  {
    return view('posts.create');
  }
  /**
   * Store a newly created resource in storage.
   *
   * @param  \Illuminate\Http\Request  $request
   * @return \Illuminate\Http\Response
   */
  public function store(Request $request)
  {
    $request->validate([
      'email' => 'email'
    ]);
    dd('Done');
  }
}

C:\xampp8\htdocs\plugindev\resources\views\posts\create.blade.php

<style>
  .error {
    color: red;
  }
</style>
<h1>Create new post</h1>
<form action="{{ route('post') }}" method="POST">
  @csrf
  <div>
    <p @error('email') class="error" @enderror>
      Title
      @error('email')
      : <span>{{ $message }}</span>
      @enderror
    </p>
    <input type="text" name="email">
  </div>
  <br>
  <div>
    <button type="submit">Create</button>
  </div>
</form>

Ends with

Trường được xác thực phải kết thúc bằng một trong các giá trị đã cho.

C:\xampp8\htdocs\plugindev\resources\views\posts\create.blade.php

<style>
  .error {
    color: red;
  }
</style>
<h1>Create new post</h1>
<form action="{{ route('post') }}" method="POST">
  @csrf
  <div>
    <p @error('text') class="error" @enderror>
      Title
      @error('text')
      : <span>{{ $message }}</span>
      @enderror
    </p>
    <input type="text" name="text">
  </div>
  <br>
  <div>
    <button type="submit">Create</button>
  </div>
</form>

C:\xampp8\htdocs\plugindev\app\Http\Controllers\PostController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class PostController extends Controller
{
  /**
   * Display a listing of the resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function index()
  {
    //
  }
  /**
   * Show the form for creating a new resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function create()
  {
    return view('posts.create');
  }
  /**
   * Store a newly created resource in storage.
   *
   * @param  \Illuminate\Http\Request  $request
   * @return \Illuminate\Http\Response
   */
  public function store(Request $request)
  {
    $request->validate([
      'text' => 'ends_with:foo,bar'
    ]);
    dd('Done');
  }
}

Exists (Database)

Trường được xác thực phải chứa giá trị tồn tại trong cột của database table. Thường dùng để kiểm tra xem ID có tồn tại trước khi thực hiện sửa hoặc xóa...

Nếu column không được chỉ định thì sẽ tự động lấy tên của trường đển gán cho column.

'id' => 'exists:users'

Trường hợp khai báo column:

'id' => 'exists:users,id'

Nếu ứng dụng của bạn sử dụng nhiều database connection, có thể sử dụng ký hiệu . để tham chiếu theo ý muốn.

'id' => 'exists:mysql.users,id'

Mặc định thì rule này sẽ sử dụng câu truy vấn:

select count(*) as aggregate from `connect.table` where `column` = value

Nếu bạn muốn thay đổi thiết lập này, bạn có thể sử dụng method Rule::exists:

use Illuminate\Validation\Rule;

'id' => [
    'other_rule',
    Rule::exists('users')->where(function ($query) {
        return $query->where('id', request('id'));
    })
]

Ta có thể sử dụng global helper request để lấy dữ liệu từ input id.

File

Trường được xác thực phải là tệp đã upload thành công.

C:\xampp8\htdocs\plugindev\app\Http\Controllers\PostController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\File;
class PostController extends Controller
{
  /**
   * Display a listing of the resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function index()
  {
    //
  }
  /**
   * Show the form for creating a new resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function create()
  {
    return view('posts.create');
  }
  /**
   * Store a newly created resource in storage.
   *
   * @param  \Illuminate\Http\Request  $request
   * @return \Illuminate\Http\Response
   */
  public function store(Request $request)
  {
    $request->validate([
      'file' => 'file'
    ]);
    $fileModel = new File;
    if ($request->file()) {
      $fileName = time() . '_' . $request->file->getClientOriginalName();
      $filePath = $request->file('file')->storeAs('uploads', $fileName, 'public');
      $fileModel->name = time() . '_' . $request->file->getClientOriginalName();
      $fileModel->file_path = '/storage/' . $filePath;
      $fileModel->save();
      return back()
        ->with('success', 'File has been uploaded.')
        ->with('file', $fileName);
    }
    dd('Done');
  }
}

C:\xampp8\htdocs\plugindev\app\Models\File.php

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class File extends Model
{
  use HasFactory;
  protected $fillable = [
    'name',
    'file_path',
  ];
}

C:\xampp8\htdocs\plugindev\database\migrations\2023_02_05_050941_create_files_table.php

C:\xampp8\htdocs\plugindev\database\migrations\2023_02_05_050941_create_files_table.php

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
  /**
   * Run the migrations.
   *
   * @return void
   */
  public function up()
  {
    Schema::create('files', function (Blueprint $table) {
      $table->id();
      $table->string('name')->nullable();
      $table->string('file_path')->nullable();
      $table->timestamps();
    });
  }
  /**
   * Reverse the migrations.
   *
   * @return void
   */
  public function down()
  {
    Schema::dropIfExists('files');
  }
};

C:\xampp8\htdocs\plugindev\resources\views\posts\create.blade.php

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
  <title>Laravel File Upload</title>
  <style>
    .container {
      max-width: 500px;
    }
    dl,
    ol,
    ul {
      margin: 0;
      padding: 0;
      list-style: none;
    }
  </style>
</head>
<body>
  <div class="container mt-5">
    <form action="{{route('post')}}" method="post" enctype="multipart/form-data">
      <h3 class="text-center mb-5">Upload File in Laravel</h3>
      @csrf
      @if ($message = Session::get('success'))
      <div class="alert alert-success">
        <strong>{{ $message }}</strong>
      </div>
      @endif
      @if (count($errors) > 0)
      <div class="alert alert-danger">
        <ul>
          @foreach ($errors->all() as $error)
          <li>{{ $error }}</li>
          @endforeach
        </ul>
      </div>
      @endif
      <div class="custom-file">
        <input type="file" name="file" class="custom-file-input" id="chooseFile">
        <label class="custom-file-label" for="chooseFile">Select file</label>
      </div>
      <button type="submit" name="submit" class="btn btn-primary btn-block mt-4">
        Upload Files
      </button>
    </form>
  </div>
</body>
</html>

Greater than

Trường được xác thực phải lớn hơn trường đã cho. Hai trường phải cùng loại dữ liệu, bao gồm: chuỗi, số, mảng và file. Về quy ước so sánh tương tự như rule between.

'gt' => [
    'numeric' => 'The :attribute must be greater than :value.',
    'file' => 'The :attribute must be greater than :value kilobytes.',
    'string' => 'The :attribute must be greater than :value characters.',
    'array' => 'The :attribute must have more than :value items.',
]

C:\xampp8\htdocs\plugindev\app\Http\Controllers\PostController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class PostController extends Controller
{
  /**
   * Display a listing of the resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function index()
  {
    //
  }
  /**
   * Show the form for creating a new resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function create()
  {
    return view('posts.create');
  }
  /**
   * Store a newly created resource in storage.
   *
   * @param  \Illuminate\Http\Request  $request
   * @return \Illuminate\Http\Response
   */
  public function store(Request $request)
  {
    $request->validate([
      'text_1' => 'gt:text_2'
    ]);
    dd('Done');
  }
}

C:\xampp8\htdocs\plugindev\resources\views\posts\create.blade.php

<style>
  .error {
    color: red;
  }
</style>
<h1>Create new post</h1>
<form action="{{ route('post') }}" method="POST">
  @csrf
  <div>
    <p @error('text_1') class="error" @enderror>
      Title
      @error('text_1')
      : <span>{{ $message }}</span>
      @enderror
    </p>
    <input type="text" name="text_1">
    <input type="text" name="text_2">
  </div>
  <br>
  <div>
    <button type="submit">Create</button>
  </div>
</form>

Greater than or equal

'gte' => [
    'numeric' => 'The :attribute must be greater than or equal :value.',
    'file' => 'The :attribute must be greater than or equal :value kilobytes.',
    'string' => 'The :attribute must be greater than or equal :value characters.',
    'array' => 'The :attribute must have :value items or more.',
]

Trường được xác thực phải lớn hơn hoặc bằng trường đã cho. Hai trường phải cùng loại dữ liệu, bao gồm: chuỗi, số, mảng và file. Về quy ước so sánh tương tự như rule between.

C:\xampp8\htdocs\plugindev\app\Http\Controllers\PostController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class PostController extends Controller
{
  /**
   * Display a listing of the resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function index()
  {
    //
  }
  /**
   * Show the form for creating a new resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function create()
  {
    return view('posts.create');
  }
  /**
   * Store a newly created resource in storage.
   *
   * @param  \Illuminate\Http\Request  $request
   * @return \Illuminate\Http\Response
   */
  public function store(Request $request)
  {
    $request->validate([
      'text_1' => 'gte:text_2'
    ]);
    dd('Done');
  }
}

C:\xampp8\htdocs\plugindev\resources\views\posts\create.blade.php

<style>
  .error {
    color: red;
  }
</style>
<h1>Create new post</h1>
<form action="{{ route('post') }}" method="POST">
  @csrf
  <div>
    <p @error('text_1') class="error" @enderror>
      Title
      @error('text_1')
      : <span>{{ $message }}</span>
      @enderror
    </p>
    <input type="text" name="text_1">
    <input type="text" name="text_2">
  </div>
  <br>
  <div>
    <button type="submit">Create</button>
  </div>
</form>

Less than

Trường được xác thực phải nhỏ hơn trường đã cho. Hai trường phải cùng loại dữ liệu, bao gồm: chuỗi, số, mảng và file. Về quy ước so sánh tương tự như rule

'lt' => [
    'numeric' => 'The :attribute must be less than :value.',
    'file' => 'The :attribute must be less than :value kilobytes.',
    'string' => 'The :attribute must be less than :value characters.',
    'array' => 'The :attribute must have less than :value items.',
]

Less than or equal

Trường được xác thực phải nhỏ hơn hoặc bằng trường đã cho. Hai trường phải cùng loại dữ liệu, bao gồm: chuỗi, số, mảng và file. Về quy ước so sánh tương tự như rule between.

'lte' => [
    'numeric' => 'The :attribute must be less than or equal :value.',
    'file' => 'The :attribute must be less than or equal :value kilobytes.',
    'string' => 'The :attribute must be less than or equal :value characters.',
    'array' => 'The :attribute must not have more than :value items.',
],

Min

rường được xác thực phải lớn hơn hoặc bằng giá trị lớn nhất cho trước, bao gồm: chuỗi, số, mảng và file. Về quy ước so sánh tương tự như rule between.

'min' => [
    'numeric' => 'The :attribute may not be greater than :max.',
    'file' => 'The :attribute may not be greater than :max kilobytes.',
    'string' => 'The :attribute may not be greater than :max characters.',
    'array' => 'The :attribute may not have more than :max items.',
],

Max

Trường được xác thực phải nhỏ hơn hoặc bằng giá trị lớn nhất cho trước, bao gồm: chuỗi, số, mảng và file. Về quy ước so sánh tương tự như rule between.

'max' => [
    'numeric' => 'The :attribute may not be greater than :max.',
    'file' => 'The :attribute may not be greater than :max kilobytes.',
    'string' => 'The :attribute may not be greater than :max characters.',
    'array' => 'The :attribute may not have more than :max items.',
],

Image

Trường được xác thực phải là tệp ảnh, bao gồm các định dạng: jpeg, png, bmp, gif, svg, hoặc webp.

C:\xampp8\htdocs\plugindev\app\Http\Controllers\PostController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class PostController extends Controller
{
  /**
   * Display a listing of the resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function index()
  {
    //
  }
  /**
   * Show the form for creating a new resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function create()
  {
    return view('posts.create');
  }
  /**
   * Store a newly created resource in storage.
   *
   * @param  \Illuminate\Http\Request  $request
   * @return \Illuminate\Http\Response
   */
  public function store(Request $request)
  {
    $request->validate([
      'avatar' => 'image'
    ]);
    dd('Done');
  }
}

C:\xampp8\htdocs\plugindev\routes\web.php

<?php
use App\Http\Controllers\PostController;
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::get('/', function () {
  return view('welcome');
});
Route::get('post/create', [PostController::class, 'create'])->name('get');
Route::post('/post', [PostController::class, 'store'])->name('post');

C:\xampp8\htdocs\plugindev\resources\views\posts\create.blade.php

<style>
  .error {
    color: red;
  }
</style>
<h1>Create new post</h1>
<form action="{{ route('post') }}" method="POST">
  @csrf
  <div>
    @foreach ($errors->all() as $error)
    <p class="error">{{ $error }}</p>
    @endforeach
    <input type="file" name="avatar">
  </div>
  <br>
  <div>
    <button type="submit">Create</button>
  </div>
</form>

IP address

Trường được xác thực phải là một phần tử nằm trong mảng đã cho.

Trường được xác thực phải một địa chỉ IP. Bao gồm các loại:

  • ip: Địa chỉ IP

  • ipv4: Địa chỉ IPv4

  • ipv6: Địa chỉ IPv6

C:\xampp8\htdocs\plugindev\app\Http\Controllers\PostController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class PostController extends Controller
{
  /**
   * Display a listing of the resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function index()
  {
    //
  }
  /**
   * Show the form for creating a new resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function create()
  {
    return view('posts.create');
  }
  /**
   * Store a newly created resource in storage.
   *
   * @param  \Illuminate\Http\Request  $request
   * @return \Illuminate\Http\Response
   */
  public function store(Request $request)
  {
    $request->validate([
      'ip' => 'ip'
    ]);
    dd('Done');
  }
}

C:\xampp8\htdocs\plugindev\resources\views\posts\create.blade.php

<style>
  .error {
    color: red;
  }
</style>
<h1>Create new post</h1>
<form action="{{ route('post') }}" method="POST">
  @csrf
  <div>
    @foreach ($errors->all() as $error)
    <p class="error">{{ $error }}</p>
    @endforeach
    <input type="text" name="ip">
  </div>
  <br>
  <div>
    <button type="submit">Create</button>
  </div>
</form>

String json

Trường được xác thực phải là một chuỗi JSON hợp lệ.

C:\xampp8\htdocs\plugindev\resources\views\posts\create.blade.php

<style>
  .error {
    color: red;
  }
</style>
<h1>Create new post</h1>
<form action="{{ route('post') }}" method="POST">
  @csrf
  <div>
    @foreach ($errors->all() as $error)
    <p class="error">{{ $error }}</p>
    @endforeach
    <textarea name="string_json" cols="30" rows="10"></textarea>
  </div>
  <br>
  <div>
    <button type="submit">Create</button>
  </div>
</form>

C:\xampp8\htdocs\plugindev\app\Http\Controllers\PostController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class PostController extends Controller
{
  /**
   * Display a listing of the resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function index()
  {
    //
  }
  /**
   * Show the form for creating a new resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function create()
  {
    return view('posts.create');
  }
  /**
   * Store a newly created resource in storage.
   *
   * @param  \Illuminate\Http\Request  $request
   * @return \Illuminate\Http\Response
   */
  public function store(Request $request)
  {
    $request->validate([
      'string_json' => 'json'
    ]);
    dd('Done');
  }
}

MIME types (Nó không hoạt động 1 mình mà kết hợp với Extension (File)

File được xác thực phải khớp với một trong các MIME đã cho. Để xác thực được MIME của file, nội dung file sẽ được đọc và framework sẽ dự đoán loại MIME, điều này có thể khác với loại MIME cho người dùng cung cấp.

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

Extension (File)

File được xác thực phải khớp với một trong các định dạng mở rộng đã cho. Rule này sẽ xác thực MIME trước thông qua đọc nội dụng file và đoán rồi mới xác thực định dạng mở rộng. Có thể nói đây là một rule mở rộng của mimetypes. Bạn có thể tham khảo một số các MIME tại

C:\xampp8\htdocs\plugindev\app\Http\Controllers\PostController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class PostController extends Controller
{
  /**
   * Display a listing of the resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function index()
  {
    //
  }
  /**
   * Show the form for creating a new resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function create()
  {
    return view('posts.create');
  }
  /**
   * Store a newly created resource in storage.
   *
   * @param  \Illuminate\Http\Request  $request
   * @return \Illuminate\Http\Response
   */
  public function store(Request $request)
  {
    $request->validate([
      'video' => 'mimes:mp4'
    ]);
    dd("done1");
  }
}

C:\xampp8\htdocs\plugindev\resources\views\posts\create.blade.php

<!DOCTYPE html>
<html>
<head>
  <title>Laravel Validation Mimes Foo,Bar,... Example</title>
  <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
  <div class="container">
    <h2>Laravel Validation Mimes Foo,Bar,... Example</h2>
    <form method="POST" action="{{ route('post') }}" autocomplete="off" enctype="multipart/form-data">
      <input type="hidden" name="_token" value="{{ csrf_token() }}">
      @if(count($errors))
      <div class="alert alert-danger">
        <strong>Whoops!</strong> There were some problems with your input.
        <br />
        <ul>
          @foreach($errors->all() as $error)
          <li>{{ $error }}</li>
          @endforeach
        </ul>
      </div>
      @endif
      <div class="row">
        <div class="col-md-12">
          <div class="form-group {{ $errors->has('video') ? 'has-error' : '' }}">
            <label for="video">Video</label>
            <input type="file" id="video" name="video" class="form-control" placeholder="Enter video">
            <span class="text-danger">{{ $errors->first('video') }}</span>
          </div>
        </div>
      </div>
      <div class="form-group">
        <button class="btn btn-success">Submit</button>
      </div>
    </form>
  </div>
</body>
</html>

Thêm mở rộng C:\xampp8\htdocs\plugindev\app\Http\Controllers\PostController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class PostController extends Controller
{
  /**
   * Display a listing of the resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function index()
  {
    //
  }
  /**
   * Show the form for creating a new resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function create()
  {
    return view('posts.create');
  }
  /**
   * Store a newly created resource in storage.
   *
   * @param  \Illuminate\Http\Request  $request
   * @return \Illuminate\Http\Response
   */
  public function store(Request $request)
  {
    $request->validate([
      'video' => 'mimes:mp4|mimetypes:video/mp4'
    ]);
    dd("done1");
  }
}

Regex

Trường được xác thực phải khớp với regular expression đã cho. Rule này bản chất sử dụng hàm preg_match trong PHP, do đó cần chú ý đến các ký tự của chuỗi pattern.

C:\xampp8\htdocs\plugindev\app\Http\Controllers\PostController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class PostController extends Controller
{
  /**
   * Display a listing of the resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function index()
  {
    //
  }
  /**
   * Show the form for creating a new resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function create()
  {
    return view('posts.create');
  }
  /**
   * Store a newly created resource in storage.
   *
   * @param  \Illuminate\Http\Request  $request
   * @return \Illuminate\Http\Response
   */
  public function store(Request $request)
  {
    $request->validate([
      'text' => 'regex:/^[a-z]+$/'
    ]);
    dd("done1");
  }
}

C:\xampp8\htdocs\plugindev\resources\views\posts\create.blade.php

<!DOCTYPE html>
<html>
<head>
  <title>Laravel Validation Mimes Foo,Bar,... Example</title>
  <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
  <div class="container">
    <h2>Laravel Validation Mimes Foo,Bar,... Example</h2>
    <form method="POST" action="{{ route('post') }}" autocomplete="off" enctype="multipart/form-data">
      <input type="hidden" name="_token" value="{{ csrf_token() }}">
      @if(count($errors))
      <div class="alert alert-danger">
        <strong>Whoops!</strong> There were some problems with your input.
        <br />
        <ul>
          @foreach($errors->all() as $error)
          <li>{{ $error }}</li>
          @endforeach
        </ul>
      </div>
      @endif
      <div class="row">
        <div class="col-md-12">
          <div class="form-group">
            <input type="text" name="text">
          </div>
        </div>
      </div>
      <div class="form-group">
        <button class="btn btn-success">Submit</button>
      </div>
    </form>
  </div>
</body>
</html>

Not regex

Trường được xác thực không được khớp với regular expression đã cho. Rule này bản chất sử dụng hàm preg_match trong PHP, do đó cần chú ý đến các ký tự của chuỗi pattern.

C:\xampp8\htdocs\plugindev\routes\web.php

<?php
use App\Http\Controllers\PostController;
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::get('/', function () {
  return view('welcome');
});
Route::get('post/create', [PostController::class, 'create'])->name('get');
Route::post('/post', [PostController::class, 'store'])->name('post');

C:\xampp8\htdocs\plugindev\app\Http\Controllers\PostController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class PostController extends Controller
{
  /**
   * Display a listing of the resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function index()
  {
    //
  }
  /**
   * Show the form for creating a new resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function create()
  {
    return view('posts.create');
  }
  /**
   * Store a newly created resource in storage.
   *
   * @param  \Illuminate\Http\Request  $request
   * @return \Illuminate\Http\Response
   */
  public function store(Request $request)
  {
    $request->validate([
      'text' => 'not_regex:/^[a-z]+$/'
    ]);
    dd("done1");
  }
}

C:\xampp8\htdocs\plugindev\resources\views\posts\create.blade.php

<!DOCTYPE html>
<html>
<head>
  <title>Laravel Validation Mimes Foo,Bar,... Example</title>
  <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
  <div class="container">
    <h2>Laravel Validation Mimes Foo,Bar,... Example</h2>
    <form method="POST" action="{{ route('post') }}" autocomplete="off" enctype="multipart/form-data">
      <input type="hidden" name="_token" value="{{ csrf_token() }}">
      @if(count($errors))
      <div class="alert alert-danger">
        <strong>Whoops!</strong> There were some problems with your input.
        <br />
        <ul>
          @foreach($errors->all() as $error)
          <li>{{ $error }}</li>
          @endforeach
        </ul>
      </div>
      @endif
      <div class="row">
        <div class="col-md-12">
          <div class="form-group">
            <input type="text" name="text">
          </div>
        </div>
      </div>
      <div class="form-group">
        <button class="btn btn-success">Submit</button>
      </div>
    </form>
  </div>
</body>
</html>

Nullable

Trường được xác thực có thể nhận giá trị null, nếu không thì phải tuân thủ các validation rule còn lại.

C:\xampp8\htdocs\plugindev\app\Http\Controllers\PostController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class PostController extends Controller
{
  /**
   * Display a listing of the resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function index()
  {
    //
  }
  /**
   * Show the form for creating a new resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function create()
  {
    return view('posts.create');
  }
  /**
   * Store a newly created resource in storage.
   *
   * @param  \Illuminate\Http\Request  $request
   * @return \Illuminate\Http\Response
   */
  public function store(Request $request)
  {
    $request->validate([
      'text' => 'nullable|alpha'
    ]);
    dd("done1");
  }
}

C:\xampp8\htdocs\plugindev\resources\views\posts\create.blade.php

<!DOCTYPE html>
<html>
<head>
  <title>Laravel Validation Mimes Foo,Bar,... Example</title>
  <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
  <div class="container">
    <h2>Laravel Validation Mimes Foo,Bar,... Example</h2>
    <form method="POST" action="{{ route('post') }}" autocomplete="off" enctype="multipart/form-data">
      <input type="hidden" name="_token" value="{{ csrf_token() }}">
      @if(count($errors))
      <div class="alert alert-danger">
        <strong>Whoops!</strong> There were some problems with your input.
        <br />
        <ul>
          @foreach($errors->all() as $error)
          <li>{{ $error }}</li>
          @endforeach
        </ul>
      </div>
      @endif
      <div class="row">
        <div class="col-md-12">
          <div class="form-group">
            <input type="text" name="text">
          </div>
        </div>
      </div>
      <div class="form-group">
        <button class="btn btn-success">Submit</button>
      </div>
    </form>
  </div>
</body>
</html>

Present

Trường được xác thực phải có mặt trong request nhưng có thể trống.

C:\xampp8\htdocs\plugindev\app\Http\Controllers\PostController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class PostController extends Controller
{
  /**
   * Display a listing of the resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function index()
  {
    //
  }
  /**
   * Show the form for creating a new resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function create()
  {
    return view('posts.create');
  }
  /**
   * Store a newly created resource in storage.
   *
   * @param  \Illuminate\Http\Request  $request
   * @return \Illuminate\Http\Response
   */
  public function store(Request $request)
  {
    $request->validate([
      'name' => 'present',
      'short_code' => 'required'
    ]);
    dd("done1");
  }
}

C:\xampp8\htdocs\plugindev\resources\views\posts\create.blade.php

<!DOCTYPE html>
<html>
<head>
  <title>Laravel Validation Present Example</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
</head>
<body>
  <div class="container">
    <h1>Laravel Validation Present Example</h1>
    <div class="card-body">
      @if (count($errors) > 0)
      <div class="row">
        <div class="col-md-12">
          <div class="alert alert-danger alert-dismissible">
            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
            @foreach($errors->all() as $error)
            {{ $error }} <br>
            @endforeach
          </div>
        </div>
      </div>
      @endif
      {!! Form::open(array('route' => 'post','method'=>'POST')) !!}
      <div class="row">
        <div class="col-md-12">
          <div class="form-group">
            <label>Short Code</label>
            {{ Form::text('short_code', null ,['class'=>'form-control', 'placeholder'=>'Short Code'] ) }}
            @if($errors->has('short_code'))
            <span class="text-danger">{{ $errors->first('short_code') }}</span>
            @endif
          </div>
        </div>
      </div>
      <div class="row">
        <div class="col-md-12 text-center mt-2 mb-3">
          <button type="submit" class="btn btn-success">Submit</button>
        </div>
      </div>
      {!! Form::close() !!}
    </div>
  </div>
</body>
</html>

Required gần giống với Present

Trường được xác thực phải có mặt trong request và không được trống. Một trường được coi là trống nếu rơi vào các trường hợp sau:

  • Giá trị là null.

  • Giá trị là mội chuỗi trống.

  • Giá trị là một mảng trống hoặc object Countable trống (sẽ tìm hiểu ở các tập sau).

  • Giá trị là một file đã upload nhưng không tìm thấy đường dẫn.

C:\xampp8\htdocs\plugindev\app\Http\Controllers\PostController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class PostController extends Controller
{
  /**
   * Display a listing of the resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function index()
  {
    //
  }
  /**
   * Show the form for creating a new resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function create()
  {
    return view('posts.create');
  }
  /**
   * Store a newly created resource in storage.
   *
   * @param  \Illuminate\Http\Request  $request
   * @return \Illuminate\Http\Response
   */
  public function store(Request $request)
  {
    $request->validate([
      'text' => 'required'
    ]);
    dd("done1");
  }
}

C:\xampp8\htdocs\plugindev\resources\views\posts\create.blade.php

<!DOCTYPE html>
<html>
<head>
  <title>Laravel Validation Mimes Foo,Bar,... Example</title>
  <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
  <div class="container">
    <h2>Laravel Validation Mimes Foo,Bar,... Example</h2>
    <form method="POST" action="{{ route('post') }}" autocomplete="off" enctype="multipart/form-data">
      <input type="hidden" name="_token" value="{{ csrf_token() }}">
      @if(count($errors))
      <div class="alert alert-danger">
        <strong>Whoops!</strong> There were some problems with your input.
        <br />
        <ul>
          @foreach($errors->all() as $error)
          <li>{{ $error }}</li>
          @endforeach
        </ul>
      </div>
      @endif
      <div class="row">
        <div class="col-md-12">
          <div class="form-group">
            <input type="text" name="text">
          </div>
        </div>
      </div>
      <div class="form-group">
        <button class="btn btn-success">Submit</button>
      </div>
    </form>
  </div>
</body>
</html>

Required if

Trường được xác thực phải có mặt trong request và không được trống nếu như một trường khác có giá trị bằng giá trị đã cho.

Ngoài ra bạn cũng có thể sử dụng method Rule::requiredIf để linh hoạt hơn. Method này chấp nhận giá trị boolean hoặc một Closure object trả về gía trị boolean. Nếu là true thì validation rule này sẽ được thực thi.

'field' => Rule::requiredIf(boolean)
'field' => Rule::required(function () use ($request) {
    return boolean;
});

C:\xampp8\htdocs\plugindev\app\Http\Controllers\PostController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class PostController extends Controller
{
  /**
   * Display a listing of the resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function index()
  {
    //
  }
  /**
   * Show the form for creating a new resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function create()
  {
    return view('posts.create');
  }
  /**
   * Store a newly created resource in storage.
   *
   * @param  \Illuminate\Http\Request  $request
   * @return \Illuminate\Http\Response
   */
  public function store(Request $request)
  {
    $input = $request->all();
    $request->validate([
      'type' => 'required',
      'name' => 'required_if:type,student',
      'first_name' => 'required_if:type,employe',
      'last_name' => 'required_i```blade
<!DOCTYPE html>
<html>
<head>
  <title></title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" integrity="sha256-NuCn4IvuZXdBaFKJOAcsU2Q3ZpwbdFisd5dux4jkQ5w=" crossorigin="anonymous" />
  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</head>
<body>
  <div class="container">
    <div class="row">
      <div class="col-md-6 offset-3">
        <div class="card mt-5">
          <div class="card-header text-center bg-info">
            <h2 class="text-white"> <strong>Required if Validation</strong></h2>
          </div>
          <div class="card-body">
            @if (count($errors) > 0)
            <ul class="alert alert-danger">
              @foreach($errors->all() as $error)
              <li>{{ $error }}</li>
              @endforeach
            </ul>
            @endif
            <form action="{{ route('post') }}" method="post">
              @csrf
              <div class="form-group">
                <label>Type:- </label>
                <select name="type" class="form-control">
                  <option value="">--select type--</option>
                  <option value="student" @if(old('type')=="student" ) {{ 'selected' }} @endif>student</option>
                  <option value="employe" @if(old('type')=="employe" ) {{ 'selected' }} @endif>employe</option>
                </select>
              </div>
              <div class="form-group">
                <label>Name :- </label>
                <input type="text" name="name" class="form-control">
              </div>
              <div class="form-group">
                <label>First Name :- </label>
                <input type="text" name="first_name" class="form-control">
              </div>
              <div class="form-group">
                <label>Last Name :- </label>
                <input type="text" name="last_name" class="form-control">
              </div>
              <div class="text-center">
                <button class="btn btn-success"><i class="fa fa-floppy-o" aria-hidden="true"></i> Submit </button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
  </div>
</body>
</html>

```f:type,employe',
    ]);
    dd("done1");
  }
}

C:\xampp8\htdocs\plugindev\resources\views\posts\create.blade.php

<!DOCTYPE html>
<html>
<head>
  <title></title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" integrity="sha256-NuCn4IvuZXdBaFKJOAcsU2Q3ZpwbdFisd5dux4jkQ5w=" crossorigin="anonymous" />
  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</head>
<body>
  <div class="container">
    <div class="row">
      <div class="col-md-6 offset-3">
        <div class="card mt-5">
          <div class="card-header text-center bg-info">
            <h2 class="text-white"> <strong>Required if Validation</strong></h2>
          </div>
          <div class="card-body">
            @if (count($errors) > 0)
            <ul class="alert alert-danger">
              @foreach($errors->all() as $error)
              <li>{{ $error }}</li>
              @endforeach
            </ul>
            @endif
            <form action="{{ route('post') }}" method="post">
              @csrf
              <div class="form-group">
                <label>Type:- </label>
                <select name="type" class="form-control">
                  <option value="">--select type--</option>
                  <option value="student" @if(old('type')=="student" ) {{ 'selected' }} @endif>student</option>
                  <option value="employe" @if(old('type')=="employe" ) {{ 'selected' }} @endif>employe</option>
                </select>
              </div>
              <div class="form-group">
                <label>Name :- </label>
                <input type="text" name="name" class="form-control">
              </div>
              <div class="form-group">
                <label>First Name :- </label>
                <input type="text" name="first_name" class="form-control">
              </div>
              <div class="form-group">
                <label>Last Name :- </label>
                <input type="text" name="last_name" class="form-control">
              </div>
              <div class="text-center">
                <button class="btn btn-success"><i class="fa fa-floppy-o" aria-hidden="true"></i> Submit </button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
  </div>
</body>
</html>

Required unless

Trường được xác thực phải có mặt trong request và không được trống trừ khi một trường khác có giá trị bằng giá trị đã cho.

C:\xampp8\htdocs\plugindev\app\Http\Controllers\PostController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class PostController extends Controller
{
  /**
   * Display a listing of the resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function index()
  {
    //
  }
  /**
   * Show the form for creating a new resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function create()
  {
    return view('posts.create');
  }
  /**
   * Store a newly created resource in storage.
   *
   * @param  \Illuminate\Http\Request  $request
   * @return \Illuminate\Http\Response
   */
  public function store(Request $request)
  {
    $input = $request->all();
    $request->validate([
      'field' => 'required',
      'field2' => 'required_unless:field,1,2,3',
    ]);
  }
}

C:\xampp8\htdocs\plugindev\resources\views\posts\create.blade.php

<!DOCTYPE html>
<html>
<head>
  <title>Laravel Validation Mimes Foo,Bar,... Example</title>
  <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
  <div class="container">
    <h2>Laravel Validation Mimes Foo,Bar,... Example</h2>
    <form method="POST" action="{{ route('post') }}" autocomplete="off" enctype="multipart/form-data">
      <input type="hidden" name="_token" value="{{ csrf_token() }}">
      @if(count($errors))
      <div class="alert alert-danger">
        <strong>Whoops!</strong> There were some problems with your input.
        <br />
        <ul>
          @foreach($errors->all() as $error)
          <li>{{ $error }}</li>
          @endforeach
        </ul>
      </div>
      @endif
      <div class="row">
        <div class="col-md-12">
          <div class="form-group">
            <input type="text" name="field">
            <br/>
            <input type="text" name="field2">
          </div>
        </div>
      </div>
      <div class="form-group">
        <button class="btn btn-success">Submit</button>
      </div>
    </form>
  </div>
</body>
</html>

Required with

Trường được xác thực phải có mặt trong request và không được trống trừ nếu một trong các trường liệt kê có mặt trong request.

C:\xampp8\htdocs\plugindev\app\Http\Controllers\PostController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class PostController extends Controller
{
  /**
   * Display a listing of the resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function index()
  {
    //
  }
  /**
   * Show the form for creating a new resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function create()
  {
    return view('posts.create');
  }
  /**
   * Store a newly created resource in storage.
   *
   * @param  \Illuminate\Http\Request  $request
   * @return \Illuminate\Http\Response
   */
  public function store(Request $request)
  {
    $input = $request->all();
    $request->validate([
      'field' => 'required',
      'anotherfield' => 'required_with:field'
    ]);
    dd('done');
  }
}

C:\xampp8\htdocs\plugindev\resources\views\posts\create.blade.php

<!DOCTYPE html>
<html>
<head>
  <title>Laravel Validation Mimes Foo,Bar,... Example</title>
  <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
  <div class="container">
    <h2>Laravel Validation Mimes Foo,Bar,... Example</h2>
    <form method="POST" action="{{ route('post') }}" autocomplete="off" enctype="multipart/form-data">
      <input type="hidden" name="_token" value="{{ csrf_token() }}">
      @if(count($errors))
      <div class="alert alert-danger">
        <strong>Whoops!</strong> There were some problems with your input.
        <br />
        <ul>
          @foreach($errors->all() as $error)
          <li>{{ $error }}</li>
          @endforeach
        </ul>
      </div>
      @endif
      <div class="row">
        <div class="col-md-12">
          <div class="form-group">
            <input type="text" name="field">
            <br/>
            <input type="text" name="anotherfield">
          </div>
        </div>
      </div>
      <div class="form-group">
        <button class="btn btn-success">Submit</button>
      </div>
    </form>
  </div>
</body>
</html>

Required with all

Trường được xác thực phải có mặt trong request và không được trống trừ nếu tất cả các trường liệt kê có mặt trong request.

Last updated