Меню

Вывод ошибок валидации laravel

  1. 1. Введение
  2. 2. Краткое руководство по проверке ввода

    1. 2.1. Определение маршрутов
  3. 3. Создание контроллера

    1. 3.1. Написание логики проверки ввода
    2. 3.2. Вывод ошибок
  4. 4. Проверка запроса формы

    1. 4.1. Создание запроса формы
    2. 4.2. Авторизация запроса формы
    3. 4.3. Настройка формата ошибок
    4. 4.4. Настройка сообщений об ошибках
  5. 5. Создание валидаторов вручную

    1. 5.1. Автоматическая переадресация
    2. 5.2. Именованные наборы ошибок
    3. 5.3. Вебхук после проверки
  6. 6. Работа с сообщениями об ошибках

    1. 6.1. Изменение сообщений об ошибках
  7. 7. Доступные правила проверки

    1. 7.1. accepted
    2. 7.2. active_url
    3. 7.3. after:date
    4. 7.4. alpha
    5. 7.5. alpha_dash
    6. 7.6. alpha_num
    7. 7.7. array
    8. 7.8. before:date
    9. 7.9. between:min,max
    10. 7.10. boolean
    11. 7.11. confirmed
    12. 7.12. date
    13. 7.13. date_format:format
    14. 7.14. different:field
    15. 7.15. digits:value
    16. 7.16. digits_between:min,max
    17. 7.17. dimensions
    18. 7.18. distinct
    19. 7.19. email
    20. 7.20. exists:table,column
    21. 7.21. file
    22. 7.22. filled
    23. 7.23. image
    24. 7.24. in:foo,bar,…
    25. 7.25. in_array:anotherfield
    26. 7.26. integer
    27. 7.27. ip
    28. 7.28. json
    29. 7.29. max:value
    30. 7.30. mimetypes:text/plain,…
    31. 7.31. mimes:foo,bar,…
    32. 7.32. min:value
    33. 7.33. nullable
    34. 7.34. not_in:foo,bar,…
    35. 7.35. numeric
    36. 7.36. present
    37. 7.37. regex:pattern
    38. 7.38. required
    39. 7.39. required_if:anotherfield,value,…
    40. 7.40. required_unless:anotherfield,value,…
    41. 7.41. required_with:foo,bar,…
    42. 7.42. required_with_all:foo,bar,…
    43. 7.43. required_without:foo,bar,…
    44. 7.44. required_without_all:foo,bar,…
    45. 7.45. same:field
    46. 7.46. size:value
    47. 7.47. string
    48. 7.48. timezone
    49. 7.49. unique:table,column,except,idColumn
    50. 7.50. url
  8. 8. Условные правила
  9. 9. Проверка ввода массивов
  10. 10. Собственные правила проверки

Введение

Laravel предоставляет несколько разных подходов к проверке входящих в ваше приложение данных. По умолчанию базовый класс контроллера использует типаж ValidatesRequests, который предоставляет удобный метод проверки входящего HTTP-запроса с помощью различных мощных правил проверки.

Краткое руководство по проверке ввода

Для изучения мощных возможностей проверки ввода в Laravel, давайте рассмотрим полный пример проверки ввода через форму и вывода сообщений об ошибках.

Определение маршрутов

Сначала давайте предположим, что у нас есть следующие маршруты, определённые в файле routes/web.php:

PHP

Route::get('post/create''PostController@create');Route::post('post''PostController@store');

Очевидно, маршрут GET выведет пользователю форму для написания новой статьи, а маршрут POST сохранит её в БД.

Создание контроллера

Теперь давайте посмотрим на простой контроллер, который обрабатывает эти маршруты. Метод PHPstore() мы пока оставим пустым:

PHP

<?phpnamespace AppHttpControllers;

use 

IlluminateHttpRequest;
use 
AppHttpControllersController;

class 

PostController extends Controller
{
  
/**
   * Вывод формы написания статьи.
   *
   * @return Response
   */
  
public function create()
  {
    return 
view('post.create');
  }
/**
   * Сохранение новой статьи.
   *
   * @param  Request  $request
   * @return Response
   */
  
public function store(Request $request)
  {
    
// Проверка и сохранение новой статьи.
  
}
}

Написание логики проверки ввода

Теперь мы готовы наполнить метод PHPstore() логикой для проверки новой статьи. Если вы посмотрите в базовый класс контроллера приложения (AppHttpControllersController), то увидите, что в нём используется типаж ValidatesRequests. Этот типаж предоставляет удобный метод PHPvalidate() всем вашим контроллерам.

Метод PHPvalidate() принимает входящий HTTP-запрос и набор правил для проверки. Если проверка успешна, ваш код продолжит нормально выполняться. Но если проверка провалится, возникнет исключение, и пользователю будет автоматически отправлен отклик с соответствующей ошибкой. Для обычных HTTP-запросов будет сгенерирован отклик-переадресация, а для AJAX-запросов — JSON-отклик.

Для лучшего понимания метода PHPvalidate() давайте вернёмся к методу PHPstore():

PHP

/**
 * Сохранение новой статьи.
 *
 * @param  Request  $request
 * @return Response
 */
public function store(Request $request)
{
  
$this->validate($request, [
    
'title' => 'required|unique:posts|max:255',
    
'body' => 'required',
  ]);
// Статья прошла проверку, сохранение в БД...
}

Как видите, мы просто передали входящий HTTP-запрос и требуемые правила проверки в метод PHPvalidate(). Если проверка провалится, будет сгенерирован соответствующий отклик. Если проверка успешна, ваш контроллер продолжит нормально выполняться.


+
5.2

добавлено в

5.2

(08.12.2016)

Остановка после первой ошибки ввода

Иногда надо остановить выполнение правил проверки ввода для атрибута после первой ошибки. Для этого назначьте на атрибут правило bail:

PHP

  $this->validate($request, [
      
'title' => 'bail|required|unique:posts|max:255',
      
'body' => 'required',
  ]);

Если правило required на атрибуте title не выполнится, то правило unique не будет проверяться. Правила будут проверены в порядке их назначения.

Замечание о вложенных атрибутах

Если ваш HTTP-запрос содержит «вложенные» параметры, вы можете указать их в правилах проверки с помощью «точечной» записи:

PHP

$this->validate($request, [
  
'title' => 'required|unique:posts|max:255',
  
'author.name' => 'required',
  
'author.description' => 'required',
]);

Вывод ошибок

Что будет, если параметры входящего запроса не пройдут проверку? Как уже было сказано, Laravel автоматически перенаправит пользователя на предыдущую страницу. Вдобавок, все ошибки будут автоматически отправлены в сессию.

Заметьте, мы не привязывали сообщения об ошибках к представлению в нашем маршруте GET. Потому что Laravel проверяет наличие ошибок в данных сессии и автоматически привязывает их к представлению, если они доступны. Поэтому важно помнить, что переменная PHP$errors будет всегда доступна во всех ваших представлениях при каждом запросе, позволяя вам всегда рассчитывать на то, что она определена и может быть безопасно использована. Переменная PHP$errors будет экземпляром IlluminateSupportMessageBag. Более подробно о работе с этим объектом читайте в его документации.

Переменная PHP$errors привязывается к представлению посредником IlluminateViewMiddlewareShareErrorsFromSession, который входит в состав группы посредников web.

Итак, в нашем примере при неудачной проверке пользователь будет перенаправлен в метод PHPcreate() нашего контроллера, позволяя нам вывести сообщения об ошибках в представлении:

PHP

<!-- /resources/views/post/create.blade.php -->

<

h1>Написать статью</h1>

@if (

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

<!-- 

Форма написания статьи -->

Настройка формата передачи ошибок

Чтобы настроить формат ошибок проверки, передаваемых в сессию при их возникновении, переопределите formatValidationErrors в базовом контроллере. Не забудьте импортировать класс IlluminateContractsValidationValidator (для Laravel 5.0 IlluminateValidationValidator) в начале файла:

PHP

<?phpnamespace AppHttpControllers;

use 

IlluminateFoundationBusDispatchesJobs;
use 
IlluminateContractsValidationValidator;
use 
IlluminateRoutingController as BaseController;
use 
IlluminateFoundationValidationValidatesRequests;

abstract class 

Controller extends BaseController
{
  use 
DispatchesJobsValidatesRequests;/**
   * {@inheritdoc}
   */
  
protected function formatValidationErrors(Validator $validator)
  {
    return 
$validator->errors()->all();
  }
}

AJAX-запросы и проверка ввода

В этом примере мы использовали обычную форму для отправки данных в приложение. Но многие приложения используют AJAX-запросы. При использовании метода PHPvalidate() для AJAX-запросов Laravel не создаёт отклик-переадресацию. Вместо этого Laravel создаёт JSON-отклик, содержащий все возникшие при проверке ошибки. Этот JSON-отклик будет отправлен с HTTP-кодом состояния 422.

Проверка запроса формы

Создание запроса формы

Для более сложных сценариев проверки вам может понадобиться «запрос формы». Запросы формы — изменённые классы запросов, содержащие логику проверки. Для создания класса запроса формы используйте Artisan-команду shmake:request:

shphp artisan make:request StoreBlogPost

Сгенерированный класс будет помещён в папку app/Http/Requests. Если такой папки нет, она будет создана при запуске команды shmake:request. Давайте добавим несколько правил проверки в метод PHPrules():

PHP

/**
 * Получить правила проверки для применения к запросу.
 *
 * @return array
 */
public function rules()
{
  return [
    
'title' => 'required|unique|max:255',
    
'body' => 'required',
  ];
}

А как же запускаются правила проверки? Надо просто указать тип запроса в методе контроллера. Входящий запрос формы проверяется до вызова метода контроллера, это значит, что вам не надо захламлять ваш контроллер логикой проверки:

PHP

/**
 * Сохранить входящую статью.
 *
 * @param  StoreBlogPost  $request
 * @return Response
 */
public function store(StoreBlogPost $request)
{
  
// Входящий запрос прошёл проверку...
}

Если проверка неуспешна, будет сгенерирован отклик-переадресация для перенаправления пользователя на предыдущую страницу. Также в сессию будут переданы ошибки, и их можно будет отобразить. Если запрос был AJAX-запросом, то пользователю будет возвращён HTTP-отклик с кодом состояния 422, содержащий JSON-представление ошибок проверки.

Авторизация запроса формы

Класс запроса формы также содержит метод PHPauthorize(). Этим методом вы можете проверить, действительно ли у авторизованного пользователя есть право на изменение данного ресурса. Например, вы можете определить, является ли пользователь владельцем комментария, который он пытается изменить:

PHP

/**
 * Определить, авторизован ли пользователь для этого запроса.
 *
 * @return bool
 */
public function authorize()
{
  
$comment Comment::find($this->route('comment'));

  return 

$comment && $this->user()->can('update'$comment);
}

Поскольку все запросы форм наследуют базовый класс запроса Laravel, мы можем использовать метод PHPuser() для получения текущего аутентифицированного пользователя. Также обратите внимание на вызов метода PHProute() в этом примере. Этот метод даёт вам доступ к параметрам URI, определённым в вызванном маршруте, таким как параметр PHP{comment} в примере ниже:

PHP

Route::post('comment/{comment}');

Если метод PHPauthorize() возвращает false, то будет автоматически возвращён HTTP-ответ с кодом состояния 403, и метод вашего контроллера не будет выполнен.

Если вы планируете разместить логику авторизации в другой части приложения, просто верните true из метода PHPauthorize():

PHP

/**
 * Определить, авторизован ли пользователь для этого запроса.
 *
 * @return bool
 */
public function authorize()
{
  return 
true;
}

Настройка формата ошибок

Если хотите настроить формат сообщений об ошибках ввода, передаваемых в сессию при их возникновении, переопределите PHPformatErrors() в вашем базовом запросе (AppHttpRequestsRequest). Не забудьте импортировать класс IlluminateContractsValidationValidator в начале файла:

PHP

/**
 * {@inheritdoc}
 */
protected function formatErrors(Validator $validator)
{
  return 
$validator->errors()->all();
}

Настройка сообщений об ошибках

Для настройки сообщений об ошибках, используемых запросом формы, переопределите метод PHPmessages(). Этот метод должен возвращать массив пар атрибут/правило и соответствующие им сообщения об ошибках:

PHP

/**
 * Получить сообщения об ошибках для определённых правил проверки.
 *
 * @return array
 */
public function messages()
{
  return [
    
'title.required' => 'Необходимо указать заголовок',
    
'body.required'  => 'Необходимо написать статью',
  ];
}

Создание валидаторов вручную

Если вы не хотите использовать метод PHPvalidate() типажа ValidatesRequests, вы можете создать экземпляр валидатора вручную с помощью фасада Validator. Метод PHPmake() этого фасада создаёт новый экземпляр валидатора:

PHP

<?phpnamespace AppHttpControllers;

use 

Validator;
use 
IlluminateHttpRequest;
use 
AppHttpControllersController;

class 

PostController extends Controller
{
  
/**
   * Сохранить новую статью.
   *
   * @param  Request  $request
   * @return Response
   */
  
public function store(Request $request)
  {
    
$validator Validator::make($request->all(), [
      
'title' => 'required|unique:posts|max:255',
      
'body' => 'required',
    ]);

    if (

$validator->fails()) {
      return 
redirect('post/create')
                  ->
withErrors($validator)
                  ->
withInput();
    }
// Сохранить статью...
  
}
}

Первый аргумент метода PHPmake() — данные для проверки. Второй — правила, которые должны быть применены к этим данным.

Если запрос не пройдёт проверку, вы можете использовать метод PHPwithErrors(), чтобы передать сообщения об ошибках в сессию. При использовании этого метода переменная PHP$errors автоматически станет общей для ваших представлений после переадресации, позволяя вам легко выводить их пользователю. Метод PHPwithErrors() принимает валидатор, MessageBag или PHP-массив.


+
5.3

добавлено в

5.3

(28.01.2017)

Автоматическая переадресация

Если вы хотите создать экземпляр валидатора вручную, но при этом иметь возможность автоматической переадресации, предлагаемой типажом ValidatesRequest, то можете вызвать метод PHPvalidate() на существующем экземпляре валидатора. Если при проверке обнаружатся ошибки, пользователь будет автоматически переадресован, а в случае AJAX-запроса будет возвращён JSON-отклик:

PHP

Validator::make($request->all(), [
  
'title' => 'required|unique:posts|max:255',
  
'body' => 'required',
])->
validate();


+
5.0

добавлено в

5.0

(08.02.2016)

Использование массивов для указания правил

Несколько правил могут быть разделены либо прямой чертой (|), либо быть отдельными элементами массива.

PHP

$validator Validator::make(
  [
'name' => 'Ваня'],
  [
'name' => ['required''min:5']]
);

Проверка нескольких полей

PHP

$validator Validator::make(
  [
    
'name' => 'Ваня',
    
'password' => 'плохойпароль',
    
'email' => 'email@example.com'
  
],
  [
    
'name' => 'required',
    
'password' => 'required|min:8',
    
'email' => 'required|email|unique:users'
  
]
);

Когда создан экземпляр PHPValidator, метод PHPfails() (или PHPpasses()) может быть использован для проведения проверки.

PHP

if ($validator->fails()) {
  
// Переданные данные не прошли проверку
}

Если валидатор нашёл ошибки, вы можете получить его сообщения таким образом:

PHP

$messages $validator->messages();

Вы также можете получить массив правил, по которым данные не прошли проверку, без самих сообщений — с помощью метода PHPfailed():

PHP

$failed $validator->failed();

Именованные наборы ошибок

Если у вас несколько форм на одной странице, вы можете дать имена наборам ошибок MessageBag, и получать сообщения об ошибках для конкретной формы. Просто передайте имя вторым аргументом метода PHPwithErrors():

PHP

return redirect('register')
            ->
withErrors($validator'login');

Теперь вы можете обращаться к экземпляру MessageBag из переменной PHP$errors:

PHP

{{ $errors->login->first('email') }}

Вебхук после проверки

Валидатор также позволяет прикрепить обратные вызовы, которые будут запущены после завершения проверки. Это позволяет легко выполнять последующие проверки, а также добавлять сообщения об ошибках в коллекцию сообщений. Для начала используйте метод PHPafter() на экземпляре класса PHPValidator:

PHP

$validator Validator::make(...);$validator->after(function($validator) {
  if (
$this->somethingElseIsInvalid()) {
    
$validator->errors()->add('field''В этом поле что-то не так!');
  }
});

if (

$validator->fails()) {
  
//
}

Работа с сообщениями об ошибках

После вызова метода PHPerrors() (для Laravel 5.0 PHPmessages()) на экземпляре Validator вы получите объект PHPIlluminateSupportMessageBag, который имеет набор полезных методов для работы с сообщениями об ошибках. Переменная PHP$errors, которая автоматически становится доступной всем представлениям, также является экземпляром класса MessageBag.

Получение первого сообщения для поля

Для получения первого сообщения об ошибке для данного поля используйте метод PHPfirst():

PHP

$errors $validator->errors();

echo 

$errors->first('email');

Получение всех сообщений для одного поля

Для получения массива всех сообщений для данного поля используйте метод PHPget():

PHP

foreach ($errors->get('email') as $message) {
  
//
}


+
5.3

добавлено в

5.3

(28.01.2017)

При проверке массива из поля вы можете получить все сообщения по каждому элементу массива с помощью символа PHP*:

PHP

foreach ($errors->get('attachments.*') as $message) {
  
//
}

Получение всех сообщений для всех полей

Для получения массива всех сообщения для всех полей используйте метод PHPall():

PHP

foreach ($errors->all() as $message) {
  
//
}

Проверка наличия сообщения для поля

Для определения наличия сообщений об ошибках для определённого поля служит метод PHPhas():

PHP

if ($messages->has('email')) {
  
//
}


+
5.2 5.1 5.0

добавлено в

5.2

(08.12.2016)

5.1

(19.06.2016)

5.0

(08.02.2016)

Получение ошибки в заданном формате

PHP

echo $messages->first('email''<p>:message</p>');

По умолчанию сообщения форматируются в вид, который подходит для Bootstrap.

Получение всех сообщений в заданном формате

PHP

foreach ($messages->all('<li>:message</li>') as $message) {
  
//
}

Изменение сообщений об ошибках

При необходимости вы можете задать свои сообщения об ошибках проверки ввода вместо изначальных. Для этого есть несколько способов. Во-первых, вы можете передать свои сообщения третьим аргументом метода PHPValidator::make():

PHP

$messages = [
  
'required' => 'Необходимо указать :attribute.',
];
$validator Validator::make($input$rules$messages);

В этом примере обозначение :attribute будет заменено именем проверяемого поля. Вы можете использовать и другие обозначения. Например:

PHP

$messages = [
  
'same'    => ':attribute и :other должны совпадать.',
  
'size'    => ':attribute должен быть равен :size.',
  
'between' => ':attribute должен быть между :min и :max.',
  
'in'      => ':attribute должен иметь один из следующих типов: :values',
];

Указание своего сообщения для конкретного атрибута

Иногда вам может понадобиться указать своё сообщения только для конкретного поля. Вы можете сделать это с помощью «точечной» записи. Сначала укажите имя атрибута, а затем правило:

PHP

$messages = [
  
'email.required' => 'Нам надо знать ваш e-mail!',
];

Указание своих сообщений в языковых файлах

В большинстве случаев вы будете указывать свои сообщения в языковом файле, а не передавать их напрямую в Validator. Для этого добавьте свои сообщения в массив custom в языковом файле resources/lang/xx/validation.php:

PHP

'custom' => [
  
'email' => [
    
'required' => 'Нам надо знать ваш e-mail!',
  ],
],


+
5.3

добавлено в

5.3

(28.01.2017)

Указание своих атрибутов в языковых файлах

Если вы хотите заменить часть PHP:attribute в своём сообщении о проверке ввода на своё имя атрибута, вы можете указать своё имя в массиве attributes в языковом файле resources/lang/xx/validation.php:

PHP

'attributes' => [
  
'email' => 'email address',
],

Доступные правила проверки

accepted

Поле должно быть в значении yes, on, 1 или true. Это полезно для проверки принятия правил и лицензий.

active_url

after:date

Поле должно быть датой, более поздней, чем date. Строки приводятся к датам функцией strtotime:

PHP

'start_date' => 'required|date|after:tomorrow'

Вместо того, чтобы передавать строку-дату в strtotime, вы можете указать другое поле для сравнения с датой:

PHP

'finish_date' => 'required|date|after:start_date'

alpha

Поле должно содержать только латинские символы.

alpha_dash

Поле должно содержать только латинские символы, цифры, знаки подчёркивания (_) и дефисы (-).

alpha_num

Поле должно содержать только латинские символы и цифры.

array

Поле должно быть PHP-массивом (тип array).

before:date

Поле должно быть датой, более ранней, чем date. Строки приводятся к датам функцией strtotime.

between:min,max

Поле должно быть числом в диапазоне от min до max. Строки, числа и файлы трактуются аналогично правилу PHPsize.

boolean

Поле должно соответствовать логическому типу. Доступные значения: true, false, 1, 0, "1" и "0".

confirmed

Значение поля должно соответствовать значению поля с этим именем, плюс _confirmation. Например, если проверяется поле password, то на вход должно быть передано совпадающее по значению поле password_confirmation.

date

Поле должно быть правильной датой в соответствии с PHP-функцией strtotime.

date_format:format

Поле должно подходить под заданный формат. При проверке поля вы должны использовать либо date, либо date_format, но не оба сразу.

different:field

Значение проверяемого поля должно отличаться от значения поля field.

digits:value

Поле должно быть числовым и иметь длину, равную value.

digits_between:min,max

Поле должно иметь длину в диапазоне между min и max.


+
5.3 5.2

добавлено в

5.3

(28.01.2017)

5.2

(08.12.2016)

dimensions

Файл должен быть изображением с подходящими под ограничения размерами, которые указаны в параметрах правила:

PHP

'avatar' => 'dimensions:min_width=100,min_height=200'

Доступные ограничения: min_width, max_width, min_height, max_height, width, height, ratio.

Ограничение ratio должно быть задано в виде ширины, поделённой на высоту. Это можно указать выражением вида PHP3/2 или в виде нецелого числа PHP1.5:

PHP

'avatar' => 'dimensions:ratio=3/2'

distinct

При работе с массивами поле не должно содержать дублирующих значений.

PHP

'foo.*.id' => 'distinct'

email

Поле должно быть корректным адресом e-mail.

exists:table,column

Поле должно существовать в заданной таблице базы данных.

Простое использование

PHP

'state' => 'exists:states'

Указание имени поля в таблице

PHP

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


+
5.2

добавлено в

5.2

(08.12.2016)

Вы также можете указать больше условий, которые будут добавлены к запросу WHERE:

PHP

'email' => 'exists:staff,email,account_id,1'

Это условие можно обратить с помощью знака ! :

PHP

'email' => 'exists:staff,email,role,!admin'

Если передать значение NULL/NOT_NULL в запрос WHERE, то это добавит проверку значения БД на совпадение с NULL/NOT_NULL:

PHP

'email' => 'exists:staff,email,deleted_at,NULL'

'email' 

=> 'exists:staff,email,deleted_at,NOT_NULL'


+
5.3 5.2

добавлено в

5.3

(28.01.2017)

5.2

(08.12.2016)

Иногда бывает необходимо указать конкретное подключение к базе данных для запроса PHPexists. Это можно сделать, подставив имя подключения перед именем таблицы с помощью «точечного» синтаксиса:

PHP

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


+
5.3

добавлено в

5.3

(28.01.2017)

Если вы хотите изменить запрос, выполняемый правилом проверки, то можете использовать класс Rule, чтобы задать правило гибко. В этом примере мы также укажем правила проверки в виде массива, вместо использования символа PHP| для разделения правил:

PHP

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

file

Поле должно быть успешно загруженным файлом.

filled

Поле не должно быть пустым, если оно есть.

image

Загруженный файл должен быть изображением в формате JPEG, PNG, BMP, GIF или SVG.

in:foo,bar,…

Значение поля должно быть одним из перечисленных (foo, bar и т.д.).


+
5.2

добавлено в

5.2

(08.12.2016)

in_array:anotherfield

Значение в поле должно быть одним из значений поля anotherfield.

integer

Поле должно иметь корректное целочисленное значение.

ip

Поле должно быть корректным IP-адресом.

json

Поле должно быть JSON-строкой.

max:value

Значение поля должно быть меньше или равно value. Строки, числа и файлы трактуются аналогично правилу PHPsize.


+
5.2

добавлено в

5.2

(08.12.2016)

mimetypes:text/plain,…

Файл должен быть одного из перечисленных MIME-типов:

PHP

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

Для определения MIME-типа загруженного файла фреймворк прочитает его содержимое и попытается определить MIME-тип, который может отличаться от указанного клиентом.

mimes:foo,bar,…

MIME-тип загруженного файла должен быть одним из перечисленных.

Простое использование

PHP

'photo' => 'mimes:jpeg,bmp,png'

Несмотря на то, что вы просто указываете расширение файла, это правило проверяет MIME-тип файла, обращаясь к его содержимому и распознавая его MIME-тип.

Полный список MIME-типов и соответствующих им расширений можно найти по ссылке [https://svn.apache.org].

min:value

Значение поля должно быть более или равно value. Строки, числа и файлы трактуются аналогично правилу PHPsize.


+
5.3

добавлено в

5.3

(28.01.2017)

nullable

Поле может иметь значение PHPnull. Это особенно полезно при проверке таких примитивов, как строки и числа, которые могут содержать значения PHPnull.

not_in:foo,bar,…

Значение поля не должно быть одним из перечисленных (foo, bar и т.д.).

numeric

Поле должно иметь корректное числовое или дробное значение.


+
5.2

добавлено в

5.2

(08.12.2016)

present

Поле должно быть в данных ввода, но может быть пустым.

regex:pattern

Поле должно соответствовать заданному регулярному выражению.

При использовании этого правила может быть необходимо указать другие правила в виде элементов массива, вместо разделения их с помощью символа вертикальной черты, особенно если выражение содержит этот символ вертикальной черты (|).

required

Проверяемое поле должно иметь непустое значение. Поле считается «пустым», при выполнении одного из следующих условий:

  • Значение поля — NULL
  • Значение поля — пустая строка
  • Значение поля — пустой массив или пустой Countable-объект
  • Значение поля — файл для загрузки без пути

required_if:anotherfield,value,…

Проверяемое поле должно иметь непустое значение, если другое поле anotherfield имеет любое значение value.

required_unless:anotherfield,value,…

Проверяемое поле должно иметь непустое значение, если другое поле anotherfield не имеет значение value.

required_with:foo,bar,…

Проверяемое поле должно иметь непустое значение, но только если присутствует любое из перечисленных полей (foo, bar и т.д.).

required_with_all:foo,bar,…

Проверяемое поле должно иметь непустое значение, но только если присутствуют все перечисленные поля (foo, bar и т.д.).

required_without:foo,bar,…

Проверяемое поле должно иметь непустое значение, но только если не присутствует любое из перечисленных полей (foo, bar и т.д.).

required_without_all:foo,bar,…

Проверяемое поле должно иметь непустое значение, но только если не присутствуют все перечисленные поля (foo, bar и т.д.).

same:field

Поле должно иметь то же значение, что и поле field.

size:value

Поле должно иметь совпадающий с value размер. Для строк это обозначает длину, для чисел — число, для массивов — число элементов массива, для файлов — размер в килобайтах.

string

Поле должно быть строкового типа. Если вы хотите разрешить для поля значение PHPnull, назначьте на поле правило PHPnullable.

timezone

Поле должно содержать корректный идентификатор временной зоны в соответствии с PHP-функцией PHPtimezone_identifiers_list.

unique:table,column,except,idColumn

Значение поля должно быть уникальным в заданной таблице базы данных. Если column не указано, то будет использовано имя поля.

Указание имени столбца в таблице

PHP

'email' => 'unique:users,email_address'

Указание соединения с БД

Иногда вам может потребоваться задать собственное соединение для запросов к базе данных от PHPValidator. Как видно выше, правило проверки PHPunique:users будет использовать соединение с базой данных по умолчанию для запроса к базе данных. Чтобы изменить это, укажите соединение и имя таблицы, используя «точечную» запись:

PHP

'email' => 'unique:connection.users,email_address'


+
5.0

добавлено в

5.0

(08.02.2016)

PHP

$verifier App::make('validation.presence');$verifier->setConnection('connectionName');$validator Validator::make($input, [
  
'name' => 'required',
  
'password' => 'required|min:8',
  
'email' => 'required|email|unique:users',
]);
$validator->setPresenceVerifier($verifier);

Игнорирование определённого ID

Иногда бывает необходимо игнорировать конкретный ID при проверке на уникальность. Например, представим экран «изменения профиля», который содержит имя пользователя, адрес e-mail и местоположение. Разумеется, вы захотите проверить уникальность e-mail. Но если пользователь изменит только поле с именем, и не изменит e-mail, вам надо избежать возникновения ошибки из-за того, что пользователь сам уже является владельцем этого e-mail.


+
5.3

добавлено в

5.3

(28.01.2017)

Чтобы валидатор игнорировал ID пользователя, мы используем класс Rule для гибкого задания правила. В этом примере мы также укажем правила проверки в виде массива, вместо использования символа PHP| для разделения правил:

PHP

use IlluminateValidationRule;Validator::make($data, [
  
'email' => [
    
'required',
    
Rule::unique('users')->ignore($user->id),
  ],
]);

Если в вашей таблице используется первичный ключ с именем, отличающимся от id, укажите его при вызове метода PHPignore():

PHP

'email' => Rule::unique('users')->ignore($user->id'user_id')


+
5.2 5.1 5.0

добавлено в

5.2

(08.12.2016)

5.1

(19.06.2016)

5.0

(08.02.2016)

Вам надо, чтобы ошибка возникла только в том случае, когда пользователь укажет e-mail, который уже был использован другим пользователем. Чтобы правило проверки на уникальность игнорировало ID пользователя, передайте ID третьим параметром:

PHP

'email' => 'unique:users,email_address,'.$user->id

Если в вашей таблице используется первичный ключ с именем, отличающимся от id, укажите его четвёртым параметром:

PHP

'email' => 'unique:users,email_address,'.$user->id.',user_id'

Добавление дополнительных условий


+
5.3

добавлено в

5.3

(28.01.2017)

Вы также можете указать дополнительные условия запроса, изменив запрос методом PHPwhere(). Например, давайте добавим условие, которое проверяет, что PHPaccount_id равно PHP1:

PHP

'email' => Rule::unique('users')->where(function ($query) {
  
$query->where('account_id'1);
})


+
5.2 5.1 5.0

добавлено в

5.2

(08.12.2016)

5.1

(19.06.2016)

5.0

(08.02.2016)

Вы также можете указать больше условий, которые будут добавлены к запросу WHERE:

PHP

'email' => 'unique:users,email_address,NULL,id,account_id,1'

В правиле выше только строки с account_id равным 1 будут включены в проверку.

url

Поле должно быть корректным URL.

Условные правила

Проверять при наличии

В некоторых случаях вам нужно запускать проверки поля, только если оно есть во входном массиве. Чтобы быстро это сделать, добавьте правило sometimes в ваш список правил:

PHP

$v Validator::make($data, [
  
'email' => 'sometimes|required|email',
]);

В этом примере поле email будет проверено, только если оно есть в массиве $data.

Сложные условные проверки

Иногда вам может быть нужно, чтобы поле имело какое-либо значение, только если другое поле имеет значение, скажем, больше 100. Или вы можете требовать наличия двух полей, только когда также указано третье. Это легко достигается условными правилами. Сперва создайте объект PHPValidator с набором статичных правил, которые никогда не изменяются:

PHP

$v Validator::make($data, [
  
'email' => 'required|email',
  
'games' => 'required|numeric',
]);

Теперь предположим, что ваше приложения написано для коллекционеров игр. Если регистрируется коллекционер с более, чем 100 играми, то мы хотим его спросить, зачем ему такое количество. Например, у него может быть магазин игр, или может ему просто нравится их собирать. Итак, для добавления такого условного правила мы используем метод PHPsometimes() на экземпляре PHPValidator:

PHP

$v->sometimes('reason''required|max:500', function ($input) {
  return 
$input->games >= 100;
});

Первый аргумент этого метода — имя поля, которое мы проверяем. Второй аргумент — правило, которое мы хотим добавить, если переданная функция-замыкание (третий аргумент) вернёт true. Этот метод позволяет легко создавать сложные правила проверки ввода. Вы можете даже добавлять условные правила для нескольких полей одновременно:

PHP

$v->sometimes(['reason''cost'], 'required', function ($input) {
  return 
$input->games >= 100;
});

Параметр PHP$input, передаваемый замыканию — объект IlluminateSupportFluent и может использоваться для чтения проверяемого ввода и файлов.


+
5.3 5.2

добавлено в

5.3

(28.01.2017)

5.2

(08.12.2016)

Проверка ввода массивов

Проверка ввода массива из полей ввода не должна быть сложной. Например, чтобы проверить, что каждый e-mail в данном поле ввода массива уникален, можно сделать так:

PHP

$validator Validator::make($request->all(), [
  
'person.*.email' => 'email|unique:users',
  
'person.*.first_name' => 'required_with:person.*.last_name',
]);

Также вы можете использовать символ * при задании сообщений об ошибках ввода в языковых файлах, что позволяет легко использовать одно сообщение для полей на основе массивов:

PHP

'custom' => [
  
'person.*.email' => [
    
'unique' => 'Каждый пользователь должен иметь уникальный адрес e-mail',
  ]
],

Собственные правила проверки

Laravel содержит множество полезных правил, однако вам может понадобиться создать собственные. Один из способов зарегистрировать произвольное правило — через метод PHPValidator::extend(). Давайте используем этот метод в сервис-провайдере для регистрации своего правила:

PHP

<?phpnamespace AppProviders;

use 

IlluminateSupportFacadesValidator;
//для версии 5.2 и ранее:
//use Validator;
use IlluminateSupportServiceProvider;

class 

AppServiceProvider extends ServiceProvider
{
  
/**
   * Загрузка любых сервисов приложения.
   *
   * @return void
   */
  
public function boot()
  {
    
Validator::extend('foo', function ($attribute$value$parameters$validator) {
      return 
$value == 'foo';
    });
  }
/**
   * Регистрация сервис-провайдера.
   *
   * @return void
   */
  
public function register()
  {
    
//
  
}
}

Переданная функция-замыкание получает четыре аргумента: имя проверяемого поля PHP$attribute, значение поля PHP$value, массив параметров PHP$parameters, переданных правилу, и объект Validator.

Вместо замыкания в метод PHPextend() также можно передать метод класса:

PHP

Validator::extend('foo''FooValidator@validate');

Определение сообщения об ошибке

Вам также понадобится определить сообщение об ошибке для нового правила. Вы можете сделать это либо передавая его в виде массива строк в PHPValidator, либо вписав в языковой файл. Это сообщение необходимо поместить на первом уровне массива, а не в массив custom, который используется только для сообщений по конкретным полям:

PHP

"foo" => "Your input was invalid!","accepted" => "The :attribute must be accepted.",// Остальные сообщения об ошибках...


+
5.0

добавлено в

5.0

(08.02.2016)

Расширение класса PHPValidator

Вместо использования функций-замыканий для расширения набора доступных правил вы можете расширить сам класс PHPValidator. Для этого создайте класс, который наследует IlluminateValidationValidator. Вы можете добавить новые методы проверок, начав их имя с validate:

PHP

<?phpclass CustomValidator extends IlluminateValidationValidatorpublic function validateFoo($attribute$value$parameters)
  {
    return 
$value == 'foo';
  }

}

Регистрация нового класса PHPValidator

Затем вам нужно зарегистрировать собственное расширение:

PHP

Validator::resolver(function($translator$data$rules$messages)
{
  return new 
CustomValidator($translator$data$rules$messages);
});

Иногда при создании своего правила вам может понадобиться определить собственные строки-переменные для замены в сообщениях об ошибках. Это делается путём создания класса, как было описано выше, и вызовом метода PHPValidator::replacer(). Это можно сделать в методе PHPboot() сервис-провайдера:

PHP

/**
 * Загрузка любых сервисов приложения.
 *
 * @return void
 */
public function boot()
{
  
Validator::extend(...);Validator::replacer('foo', function ($message$attribute$rule$parameters) {
    return 
str_replace(...);
  });
}


+
5.0

добавлено в

5.0

(08.02.2016)

Это делается путём создания класса, как было описано выше, и добавлением функций с именами вида PHPreplaceXXX().

PHP

protected function replaceFoo($message$attribute$rule$parameters)
{
  return 
str_replace(':foo'$parameters[0], $message);
}

Неявное наследование

По умолчанию, если проверяемое поле отсутствует или имеет пустое значение по правилу required, обычные правила не запускаются, в том числе собственные правила. Например, правило unique не будет запущено для значения null:

PHP

$rules = ['name' => 'unique'];$input = ['name' => null];Validator::make($input$rules)->passes(); // true

Чтобы применять правило даже для пустых полей, правило должно считать, что поле обязательное. Для создания такого «неявного» наследования используйте метод PHPValidator::extendImplicit():

PHP

Validator::extendImplicit('foo', function ($attribute$value$parameters$validator) {
  return 
$value == 'foo';
});

«Неявное» наследование только указывает на обязательность поля. А будет ли правило пропускать пустое или отсутствующее поле или нет, зависит от вас.

Вступление

Laravel предлагает несколько разных подходов для проверки входящих данных вашего приложения. По умолчанию базовый класс контроллера Laravel использует ValidatesRequestsчерту, которая предоставляет удобный метод для проверки входящего HTTP-запроса с помощью множества мощных правил проверки.

Валидация Быстрый старт

Чтобы узнать о мощных функциях проверки Laravel, давайте рассмотрим полный пример проверки формы и отображения сообщений об ошибках пользователю.

Определение маршрутов

Сначала предположим, что в нашем файле определены следующие маршруты :routes/web.php

Route::get('post/create', 'PostController@create');

Route::post('post', 'PostController@store');

GETМаршрут будет отображать форму для пользователя , чтобы создать новое сообщение в блоге, в то время как POSTмаршрут будет хранить запись в блоге в базе данных.

Создание контроллера

Далее, давайте посмотрим на простой контроллер, который обрабатывает эти маршруты. Мы storeпока оставим метод пустым:

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;
use AppHttpControllersController;

class PostController extends Controller
{
    /**
     * Show the form to create a new blog post.
     *
     * @return Response
     */
    public function create()
    {
        return view('post.create');
    }

    /**
     * Store a new blog post.
     *
     * @param  Request  $request
     * @return Response
     */
    public function store(Request $request)
    {
        // Validate and store the blog post...
    }
}

Написание логики валидации

Теперь мы готовы заполнить наш storeметод логикой для проверки нового сообщения в блоге. Для этого мы будем использовать validateметод, предоставленный объектом. Если правила проверки пройдут, ваш код будет работать нормально; однако, если проверка не пройдена, будет выдано исключение, и правильный ответ об ошибке будет автоматически отправлен обратно пользователю. В случае традиционного HTTP-запроса будет сгенерирован ответ о перенаправлении, а JSON-ответ будет отправлен для AJAX-запросов.IlluminateHttpRequest

Чтобы лучше понять validateметод, давайте вернемся к storeметоду:

/**
 * Store a new blog post.
 *
 * @param  Request  $request
 * @return Response
 */
public function store(Request $request)
{
    $validatedData = $request->validate([
        'title' => 'required|unique:posts|max:255',
        'body' => 'required',
    ]);

    // The blog post is valid...
}

Как видите, мы передаем в метод нужные правила валидации validate. Опять же, если проверка не пройдена, автоматически генерируется правильный ответ. Если проверка пройдена, наш контроллер продолжит нормально работать.

Остановка при первом сбое проверки

Иногда может потребоваться прекратить запуск правил проверки для атрибута после первого сбоя проверки. Для этого присвойте bailправило атрибуту:

$request->validate([
    'title' => 'bail|required|unique:posts|max:255',
    'body' => 'required',
]);

В этом примере, если uniqueправило для titleатрибута не выполнено, maxправило не будет проверено. Правила будут утверждены в порядке их назначения.

Примечание о вложенных атрибутах

Если ваш HTTP-запрос содержит «вложенные» параметры, вы можете указать их в правилах проверки, используя синтаксис «точка»:

$request->validate([
    'title' => 'required|unique:posts|max:255',
    'author.name' => 'required',
    'author.description' => 'required',
]);

Отображение ошибок валидации

Итак, что если параметры входящего запроса не соответствуют заданным правилам проверки? Как упоминалось ранее, Laravel автоматически перенаправит пользователя обратно на прежнее место. Кроме того, все ошибки проверки автоматически будут мигать в сеансе .

Опять же, обратите внимание, что нам не нужно было явно привязывать сообщения об ошибках к представлению нашего GETмаршрута. Это потому, что Laravel будет проверять ошибки в данных сеанса и автоматически связывать их с представлением, если они доступны. $errorsПеременная будет экземпляром . Для получения дополнительной информации о работе с этим объектом ознакомьтесь с его документацией .IlluminateSupportMessageBag

$errorsПеременная связана с видом со стороны промежуточного программного обеспечения , которое обеспечивается в группе промежуточного программного обеспечения . Когда применяется это промежуточное программное обеспечение, переменная всегда будет доступна в ваших представлениях , что позволяет вам удобно предполагать, что переменная всегда определена и ее можно безопасно использовать.IlluminateViewMiddlewareShareErrorsFromSessionweb$errors$errors

Таким образом, в нашем примере пользователь будет перенаправлен на createметод нашего контроллера при сбое проверки, что позволит нам отображать сообщения об ошибках в представлении:

<!-- /resources/views/post/create.blade.php -->

<h1>Create Post</h1>

@if ($errors->any())
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

<!-- Create Post Form -->

@errorДиректива

Вы также можете использовать директиву @error Blade, чтобы быстро проверить, существуют ли сообщения об ошибках валидации для данного атрибута. Внутри @errorдирективы вы можете вызвать $messageпеременную для отображения сообщения об ошибке:

<!-- /resources/views/post/create.blade.php -->

<label for="title">Post Title</label>

<input id="title" type="text" class="@error('title') is-invalid @enderror">

@error('title')
    <div class="alert alert-danger">{{ $message }}</div>
@enderror

Примечание о необязательных полях

По умолчанию Laravel включает TrimStringsи ConvertEmptyStringsToNullпромежуточное ПО в глобальный стек промежуточного ПО вашего приложения. Эти промежуточные программы перечислены в стеке классом. Из-за этого вам часто нужно помечать ваши «необязательные» поля запроса так, как будто вы не хотите, чтобы валидатор считал значения недействительными. Например:AppHttpKernelnullablenull

$request->validate([
    'title' => 'required|unique:posts|max:255',
    'body' => 'required',
    'publish_at' => 'nullable|date',
]);

В этом примере мы указываем, что publish_atполе может быть либо nullдействительным представлением даты. Если nullableмодификатор не добавлен в определение правила, валидатор будет считать nullнедопустимую дату.

AJAX-запросы и валидация

В этом примере мы использовали традиционную форму для отправки данных в приложение. Однако многие приложения используют запросы AJAX. При использовании validateметода во время запроса AJAX, Laravel не будет генерировать ответ перенаправления. Вместо этого Laravel генерирует ответ JSON, содержащий все ошибки проверки. Этот ответ JSON будет отправлен с кодом состояния 422 HTTP.

Проверка запроса формы

Создание запросов формы

Для более сложных сценариев проверки вы можете создать «запрос формы». Запросы форм — это пользовательские классы запросов, которые содержат логику проверки. Чтобы создать класс запроса формы, используйте команду Artisan CLI:make:request

php artisan make:request StoreBlogPost

Сгенерированный класс будет помещен в каталог. Если этот каталог не существует, он будет создан при запуске команды. Давайте добавим несколько правил проверки в метод:app/Http/Requestsmake:requestrules

/**
 * Get the validation rules that apply to the request.
 *
 * @return array
 */
public function rules()
{
    return [
        'title' => 'required|unique:posts|max:255',
        'body' => 'required',
    ];
}

Вы можете напечатать любые зависимости, которые вам нужны, в rulesсигнатуре метода. Они будут автоматически разрешены через сервисный контейнер Laravel .

Итак, как оцениваются правила валидации? Все, что вам нужно сделать, это напечатать запрос на метод вашего контроллера. Входящий запрос формы проверяется перед вызовом метода контроллера, что означает, что вам не нужно загромождать ваш контроллер какой-либо логикой проверки:

/**
 * Store the incoming blog post.
 *
 * @param  StoreBlogPost  $request
 * @return Response
 */
public function store(StoreBlogPost $request)
{
    // The incoming request is valid...

    // Retrieve the validated input data...
    $validated = $request->validated();
}

Если проверка не пройдена, будет сгенерирован ответ о перенаправлении, чтобы отправить пользователя обратно в его предыдущее местоположение. Ошибки также будут мигать в сеансе, чтобы они были доступны для отображения. Если запрос был запросом AJAX, пользователю будет возвращен HTTP-ответ с кодом состояния 422, включая JSON-представление ошибок проверки.

Добавление после хуков для формирования запросов

Если вы хотите добавить хук «после» к запросу формы, вы можете использовать withValidatorметод. Этот метод получает полностью сконструированный валидатор, позволяющий вам вызвать любой из его методов до того, как правила валидации действительно будут оценены:

/**
 * Configure the validator instance.
 *
 * @param  IlluminateValidationValidator  $validator
 * @return void
 */
public function withValidator($validator)
{
    $validator->after(function ($validator) {
        if ($this->somethingElseIsInvalid()) {
            $validator->errors()->add('field', 'Something is wrong with this field!');
        }
    });
}

Запросы формы авторизации

Класс запроса формы также содержит authorizeметод. В рамках этого метода вы можете проверить, действительно ли аутентифицированный пользователь имеет полномочия на обновление данного ресурса. Например, вы можете определить, действительно ли пользователю принадлежит комментарий в блоге, который он пытается обновить:

/**
 * Determine if the user is authorized to make this request.
 *
 * @return bool
 */
public function authorize()
{
    $comment = Comment::find($this->route('comment'));

    return $comment && $this->user()->can('update', $comment);
}

Поскольку все запросы формы расширяют базовый класс запросов Laravel, мы можем использовать userметод для доступа к аутентифицированному в настоящее время пользователю. Также обратите внимание на вызов routeметода в примере выше. Этот метод предоставляет вам доступ к параметрам URI, определенным на вызываемом маршруте, таким как параметр в примере ниже:{comment}

Route::post('comment/{comment}');

Если authorizeметод возвращается false, HTTP-ответ с кодом состояния 403 будет автоматически возвращен, и ваш метод контроллера не будет выполнен.

Если вы планируете использовать логику авторизации в другой части вашего приложения, вернитесь trueиз authorizeметода:

/**
 * Determine if the user is authorized to make this request.
 *
 * @return bool
 */
public function authorize()
{
    return true;
}

Вы можете напечатать любые зависимости, которые вам нужны, в authorizeсигнатуре метода. Они будут автоматически разрешены через сервисный контейнер Laravel .

Настройка сообщений об ошибках

Вы можете настроить сообщения об ошибках, используемые запросом формы, переопределив messagesметод. Этот метод должен возвращать массив пар атрибут / правило и соответствующие им сообщения об ошибках:

/**
 * Get the error messages for the defined validation rules.
 *
 * @return array
 */
public function messages()
{
    return [
        'title.required' => 'A title is required',
        'body.required'  => 'A message is required',
    ];
}

Настройка атрибутов проверки

Если вы хотите, чтобы :attributeчасть вашего сообщения проверки была заменена именем настраиваемого атрибута, вы можете указать настраиваемые имена, переопределив attributesметод. Этот метод должен возвращать массив пар атрибут / имя:

/**
 * Get custom attributes for validator errors.
 *
 * @return array
 */
public function attributes()
{
    return [
        'email' => 'email address',
    ];
}

Создание валидаторов вручную

Если вы не хотите использовать validateметод в запросе, вы можете создать экземпляр валидатора вручную, используя Validator фасад . makeМетод на фасаде создает новый экземпляр валидатора:

<?php

namespace AppHttpControllers;

use Validator;
use IlluminateHttpRequest;
use AppHttpControllersController;

class PostController extends Controller
{
    /**
     * Store a new blog post.
     *
     * @param  Request  $request
     * @return Response
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'title' => 'required|unique:posts|max:255',
            'body' => 'required',
        ]);

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

        // Store the blog post...
    }
}

Первым аргументом, переданным makeметоду, являются проверяемые данные. Второй аргумент — это правила проверки, которые должны применяться к данным.

После проверки, не прошла ли проверка запроса, вы можете использовать этот withErrorsметод для отправки сообщений об ошибках в сеанс. При использовании этого метода $errorsпеременная будет автоматически предоставлена ​​вашим представлениям после перенаправления, что позволит вам легко отображать их обратно пользователю. withErrorsМетод принимает валидатор, а MessageBag, или PHP array.

Автоматическое перенаправление

Если вы хотите создать экземпляр валидатора вручную, но все же воспользоваться преимуществами автоматического перенаправления, предлагаемого методом запросов validate, вы можете вызвать validateметод в существующем экземпляре валидатора. Если проверка не пройдена, пользователь будет автоматически перенаправлен или, в случае запроса AJAX, будет возвращен ответ JSON:

Validator::make($request->all(), [
    'title' => 'required|unique:posts|max:255',
    'body' => 'required',
])->validate();

Именованные пакеты с ошибками

Если у вас есть несколько форм на одной странице, вы можете назвать имена MessageBagошибок, что позволит вам получать сообщения об ошибках для конкретной формы. Передайте имя в качестве второго аргумента withErrors:

return redirect('register')
            ->withErrors($validator, 'login');

Затем вы можете получить доступ к именованному MessageBagэкземпляру из $errorsпеременной:

{{ $errors->login->first('email') }}

После проверки крюк

Валидатор также позволяет вам добавлять обратные вызовы, которые будут выполняться после завершения проверки. Это позволяет вам легко выполнять дальнейшую проверку и даже добавлять больше сообщений об ошибках в коллекцию сообщений. Чтобы начать, используйте afterметод на экземпляре валидатора:

$validator = Validator::make(...);

$validator->after(function ($validator) {
    if ($this->somethingElseIsInvalid()) {
        $validator->errors()->add('field', 'Something is wrong with this field!');
    }
});

if ($validator->fails()) {
    //
}

Работа с сообщениями об ошибках

После вызова errorsметода для Validatorэкземпляра вы получите экземпляр, который имеет множество удобных методов для работы с сообщениями об ошибках. Переменная , которая автоматически становится доступной для всех представлений также является экземпляром класса.IlluminateSupportMessageBag$errorsMessageBag

Получение первого сообщения об ошибке для поля

Чтобы получить первое сообщение об ошибке для данного поля, используйте firstметод:

$errors = $validator->errors();

echo $errors->first('email');

Получение всех сообщений об ошибках для поля

Если вам нужно получить массив всех сообщений для данного поля, используйте getметод:

foreach ($errors->get('email') as $message) {
    //
}

Если вы проверяете поле формы массива, вы можете получить все сообщения для каждого из элементов массива, используя *символ:

foreach ($errors->get('attachments.*') as $message) {
    //
}

Получение всех сообщений об ошибках для всех полей

Чтобы получить массив всех сообщений для всех полей, используйте allметод:

foreach ($errors->all() as $message) {
    //
}

Определение наличия сообщений для поля

hasМетод может быть использован , чтобы определить , существуют ли какие — либо сообщения об ошибках для данного поля:

if ($errors->has('email')) {
    //
}

Пользовательские сообщения об ошибках

При необходимости вы можете использовать пользовательские сообщения об ошибках для проверки вместо значений по умолчанию. Есть несколько способов указать пользовательские сообщения. Во-первых, вы можете передать пользовательские сообщения в качестве третьего аргумента методу:Validator::make

$messages = [
    'required' => 'The :attribute field is required.',
];

$validator = Validator::make($input, $rules, $messages);

В этом примере :attributeзаполнитель будет заменен действительным именем проверяемого поля. Вы также можете использовать другие заполнители в сообщениях проверки. Например:

$messages = [
    'same'    => 'The :attribute and :other must match.',
    'size'    => 'The :attribute must be exactly :size.',
    'between' => 'The :attribute value :input is not between :min - :max.',
    'in'      => 'The :attribute must be one of the following types: :values',
];

Указание пользовательского сообщения для данного атрибута

Иногда вам может потребоваться указать пользовательское сообщение об ошибке только для определенного поля. Вы можете сделать это, используя обозначение «точка». Сначала укажите имя атрибута, а затем правило:

$messages = [
    'email.required' => 'We need to know your e-mail address!',
];

Указание пользовательских сообщений в языковых файлах

В большинстве случаев вы, вероятно, будете указывать свои пользовательские сообщения в языковом файле, а не передавать их непосредственно в Validator. Для этого добавьте ваши сообщения в customмассив в языковой файл.resources/lang/xx/validation.php

'custom' => [
    'email' => [
        'required' => 'We need to know your e-mail address!',
    ],
],

Указание пользовательских атрибутов в языковых файлах

Если вы хотите, чтобы :attributeчасть вашего сообщения проверки была заменена именем настраиваемого атрибута, вы можете указать это имя в attributesмассиве вашего языкового файла:resources/lang/xx/validation.php

'attributes' => [
    'email' => 'email address',
],

Указание пользовательских значений в языковых файлах

Иногда вам может понадобиться :valueзаменить часть вашего сообщения для проверки пользовательским представлением значения. Например, рассмотрим следующее правило, которое указывает, что номер кредитной карты требуется, если значение payment_typeимеет cc:

$request->validate([
    'credit_card_number' => 'required_if:payment_type,cc'
]);

Если это правило проверки не выполнено, оно выдаст следующее сообщение об ошибке:

The credit card number field is required when payment type is cc.

Вместо отображения ccв качестве значения типа платежа вы можете указать представление пользовательского значения в вашем validationязыковом файле, определив valuesмассив:

'values' => [
    'payment_type' => [
        'cc' => 'credit card'
    ],
],

Теперь, если правило проверки не выполнено, оно выдаст следующее сообщение:

The credit card number field is required when payment type is credit card.

Доступные правила проверки

Ниже приведен список всех доступных правил проверки и их функции:

  • Accepted
  • Active URL
  • After (Date)
  • After Or Equal (Date)
  • Alpha
  • Alpha Dash
  • Alpha Numeric
  • Array
  • Bail
  • Before (Date)
  • Before Or Equal (Date)
  • Between
  • Boolean
  • Confirmed
  • Date
  • Date Equals
  • Date Format
  • Different
  • Digits
  • Digits Between
  • Dimensions (Image Files)
  • Distinct
  • E-Mail
  • Ends With
  • Exists (Database)
  • File
  • Filled
  • Greater Than
  • Greater Than Or Equal
  • Image (File)
  • In
  • In Array
  • Integer
  • IP Address
  • JSON
  • Less Than
  • Less Than Or Equal
  • Max
  • MIME Types
  • MIME Type By File Extension
  • Min
  • Not In
  • Not Regex
  • Nullable
  • Numeric
  • Present
  • Regular Expression
  • Required
  • Required If
  • Required Unless
  • Required With
  • Required With All
  • Required Without
  • Required Without All
  • Same
  • Size
  • Sometimes
  • Starts With
  • String
  • Timezone
  • Unique (Database)
  • URL
  • UUID

accepted

Проверяемое поле должно быть yes , on , 1 или true . Это полезно для подтверждения принятия «Условий обслуживания».

active_url

Проверяемое поле должно иметь действительную запись A или AAAA в соответствии с dns_get_recordфункцией PHP.

after (Date)

Проверяемое поле должно быть значением после указанной даты. Даты будут переданы в strtotimeфункцию PHP:

'start_date' => 'required|date|after:tomorrow'

Вместо того, чтобы передавать строку даты для оценки strtotime, вы можете указать другое поле для сравнения с датой:

'finish_date' => 'required|date|after:start_date'

after_or_equal: date

Проверяемое поле должно быть значением после или равным указанной дате. Для получения дополнительной информации см. Правило после .

alpha

Проверяемое поле должно состоять исключительно из буквенных символов.

alpha_dash

Проверяемое поле может содержать буквенно-цифровые символы, а также тире и подчеркивания.

alpha_num

Проверяемое поле должно состоять из буквенно-цифровых символов.

array

Проверяемое поле должно быть PHP array.

bail

Прекратите запуск правил проверки после первого сбоя проверки.

before (Date)

Проверяемое поле должно быть значением, предшествующим данной дате. Даты будут переданы в strtotimeфункцию PHP . Кроме того, как afterправило, в качестве значения можно указать имя другого проверяемого поля date.

before Or Equal (Date)

Проверяемое поле должно быть значением, предшествующим или равным указанной дате. Даты будут переданы в strtotimeфункцию PHP . Кроме того, как afterправило, в качестве значения можно указать имя другого проверяемого поля date.

between:min,max

Проверяемое поле должно иметь размер от заданного минимального до максимального значения . Строки, числа, массивы и файлы оцениваются так же, как sizeправило.

boolean

Проверяемое поле должно быть в состоянии быть логическим. Принимаемые входные truefalse10"1", и "0".

confirmed

Проверяемое поле должно иметь соответствующее поле foo_confirmation. Например, если проверяемое поле имеет значение password, соответствующее password_confirmationполе должно присутствовать во входных данных.

date

Проверяемое поле должно быть действительной, не относительной датой в соответствии с strtotimeфункцией PHP.

date_equals: date

Проверяемое поле должно быть равно заданной дате. Даты будут переданы в strtotimeфункцию PHP .

date_format: format

Проверяемое поле должно соответствовать заданному формату . Вы должны использовать либоdate или date_formatпри проверке поля, но не оба.

different:field

Проверяемое поле должно иметь значение, отличное от поля .

digits:value

Проверяемое поле должно быть числовым и иметь точную длину значения .

digits_between:min,max

Проверяемое поле должно иметь длину от заданного минимального до максимального значения .

dimensions

Проверяемый файл должен быть изображением, соответствующим ограничениям размеров, указанным в параметрах правила:

'avatar' => 'dimensions:min_width=100,min_height=200'

Доступны следующие ограничения: min_width , max_width , min_height , max_height , ширина , высота , коэффициент .

Отношение ограничение должно быть представлено в виде ширины , деленная на высоту. Это может быть указано либо с помощью оператора like или с плавающей точкой :3/21.5

'avatar' => 'dimensions:ratio=3/2'

Так как это правило требует нескольких аргументов, вы можете использовать метод для свободного создания правила:Rule::dimensions

use IlluminateValidationRule;

Validator::make($data, [
    'avatar' => [
        'required',
        Rule::dimensions()->maxWidth(1000)->maxHeight(500)->ratio(3 / 2),
    ],
]);

distinct

При работе с массивами проверяемое поле не должно иметь повторяющихся значений.

'foo.*.id' => 'distinct'

email

Проверяемое поле должно быть отформатировано как адрес электронной почты.

ends_with:foo,bar,…

Проверяемое поле должно заканчиваться одним из указанных значений.

exists:table,column

Проверяемое поле должно существовать в данной таблице базы данных.

Основное использование правила существования

'state' => 'exists:states'

Если columnопция не указана, будет использовано имя поля.

Указание пользовательского имени столбца

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

Иногда вам может потребоваться указать конкретное соединение с базой данных, которое будет использоваться для existsзапроса. Это можно сделать, добавив имя соединения к имени таблицы, используя синтаксис «точка»:

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

Если вы хотите настроить запрос, выполняемый правилом валидации, вы можете использовать Ruleкласс для свободного определения правила. В этом примере мы также указываем правила проверки в виде массива вместо использования |символа для их разделения:

use IlluminateValidationRule;

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

file

Проверяемое поле должно быть успешно загруженным файлом.

filled

Проверяемое поле не должно быть пустым, если оно присутствует.

gt:field

Проверяемое поле должно быть больше указанного поля . Два поля должны быть одного типа. Строки, числа, массивы и файлы оцениваются с использованием тех же соглашений, что и sizeправило.

gte:field

Проверяемое поле должно быть больше или равно данному полю . Два поля должны быть одного типа. Строки, числа, массивы и файлы оцениваются с использованием тех же соглашений, что и sizeправило.

image

Проверяемый файл должен быть изображением (jpeg, png, bmp, gif или svg)

in:foo,bar,…

Проверяемое поле должно быть включено в данный список значений. Поскольку для этого правила часто требуется implodeмассив, метод может быть использован для свободного построения правила:Rule::in

use IlluminateValidationRule;

Validator::make($data, [
    'zones' => [
        'required',
        Rule::in(['first-zone', 'second-zone']),
    ],
]);

in_array:anotherfield.*

Проверяемое поле должно существовать в значениях другого поля .

integer

Проверяемое поле должно быть целым числом.

ip

Проверяемое поле должно быть IP-адресом.

ipv4

Проверяемое поле должно быть адресом IPv4.

ipv6

Проверяемое поле должно быть адресом IPv6.

json

Проверяемое поле должно быть допустимой строкой JSON.

lt:field

Проверяемое поле должно быть меньше указанного поля . Два поля должны быть одного типа. Строки, числа, массивы и файлы оцениваются с использованием тех же соглашений, что и sizeправило.

lte:field

Проверяемое поле должно быть меньше или равно данному полю . Два поля должны быть одного типа. Строки, числа, массивы и файлы оцениваются с использованием тех же соглашений, что и sizeправило.

max:value

Проверяемое поле должно быть меньше или равно максимальному значению . Строки, числа, массивы и файлы оцениваются так же, как sizeправило.

mimetypes:text/plain,…

Проверяемый файл должен соответствовать одному из указанных типов MIME:

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

Чтобы определить тип MIME загруженного файла, его содержимое будет прочитано, и платформа попытается угадать тип MIME, который может отличаться от типа MIME, предоставленного клиентом.

mimes:foo,bar,…

Проверяемый файл должен иметь тип MIME, соответствующий одному из перечисленных расширений.

Основное использование правила MIME

'photo' => 'mimes:jpeg,bmp,png'

Несмотря на то, что вам нужно только указать расширения, это правило фактически проверяет тип файла MIME, читая содержимое файла и угадывая его тип MIME.

Полный список типов MIME и их соответствующих расширений можно найти по следующему адресу : https://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types.

min:value

Проверяемое поле должно иметь минимальное значение . Строки, числа, массивы и файлы оцениваются так же, как sizeправило.

not_in:foo,bar,…

Проверяемое поле не должно быть включено в данный список значений. Метод может быть использован для построения свободно правила:Rule::notIn

use IlluminateValidationRule;

Validator::make($data, [
    'toppings' => [
        'required',
        Rule::notIn(['sprinkles', 'cherries']),
    ],
]);

not_regex:pattern

Проверяемое поле не должно соответствовать заданному регулярному выражению.

Внутренне это правило использует preg_matchфункцию PHP . Указанный шаблон должен соответствовать форматированию, требуемому для этого, preg_matchи, следовательно, также включать допустимые разделители. Например: .'email' => 'not_regex:/^.+$/i'

Примечание. При использовании шаблонов regexnot_regexможет потребоваться указать правила в массиве вместо использования разделителей канала, особенно если регулярное выражение содержит символ канала.

nullable

Проверяемое поле может быть null. Это особенно полезно при проверке примитивов, таких как строки и целые числа, которые могут содержать nullзначения.

numeric

Проверяемое поле должно быть числовым.

present

Проверяемое поле должно присутствовать во входных данных, но может быть пустым.

regex:pattern

Проверяемое поле должно соответствовать заданному регулярному выражению.

Внутренне это правило использует preg_matchфункцию PHP . Указанный шаблон должен соответствовать форматированию, требуемому для этого, preg_matchи, следовательно, также включать допустимые разделители. Например: .'email' => 'regex:/^.+@.+$/i'

Примечание. При использовании шаблонов regexnot_regexможет потребоваться указать правила в массиве вместо использования разделителей канала, особенно если регулярное выражение содержит символ канала.

required

Проверяемое поле должно присутствовать во входных данных и не быть пустым. Поле считается «пустым», если выполняется одно из следующих условий:

  • Значение есть null.
  • Значение является пустой строкой.
  • Значением является пустой массив или пустой Countableобъект.
  • Значением является загруженный файл без пути.

required_if:anotherfield,value,…

Проверяемое поле должно присутствовать и не быть пустым, если поле другого поля равно какому-либо значению .

Если вы хотите построить более сложное условие для required_ifправила, вы можете использовать метод. Этот метод принимает логическое значение или замыкание. Когда передано Закрытие, Закрытие должно возвратиться или указать, требуется ли проверяемое поле:Rule::requiredIftruefalse

use IlluminateValidationRule;

Validator::make($request->all(), [
    'role_id' => Rule::requiredIf($request->user()->is_admin),
]);

Validator::make($request->all(), [
    'role_id' => Rule::requiredIf(function () use ($request) {
        return $request->user()->is_admin;
    }),
]);

required_unless:anotherfield,value,…

Проверяемое поле должно присутствовать и не быть пустым, если поле другого поля не равно какому-либо значению .

required_with:foo,bar,…

Проверяемое поле должно присутствовать и не быть пустым, только если присутствуют какие-либо другие указанные поля.

required_with_all:foo,bar,…

Проверяемое поле должно присутствовать и не быть пустым, только если присутствуют все другие указанные поля.

required_without:foo,bar,…

Проверяемое поле должно присутствовать и не быть пустым, только если нет других указанных полей.

required_without_all:foo,bar,…

Проверяемое поле должно присутствовать и не быть пустым, только если все другие указанные поля отсутствуют.

same:field

Данное поле должно соответствовать проверяемому полю.

size:value

Проверяемое поле должно иметь размер, соответствующий заданному значению . Для строковых данных значение соответствует количеству символов. Для числовых данных значениесоответствует заданному целочисленному значению. Для массива размер соответствует countмассиву. Для файлов размер соответствует размеру файла в килобайтах.

starts_with:foo,bar,…

Проверяемое поле должно начинаться с одного из указанных значений.

string

Проверяемое поле должно быть строкой. Если вы хотите, чтобы поле также было null, вы должны назначить nullableправило для поля.

timezone

Проверяемое поле должно быть действительным идентификатором часового пояса в соответствии с timezone_identifiers_listфункцией PHP.

unique:table,column,except,idColumn

Проверяемое поле не должно существовать в данной таблице базы данных.

Указание пользовательского имени столбца:

columnВариант может быть использован для определения соответствующего столбца базы данных в полях. Если columnопция не указана, будет использовано имя поля.

'email' => 'unique:users,email_address'

Настраиваемое соединение с базой данных

Иногда вам может понадобиться установить пользовательское соединение для запросов к базе данных, выполняемых валидатором. Как показано выше, при настройке в качестве правила проверки будет использоваться соединение с базой данных по умолчанию для запроса к базе данных. Чтобы переопределить это, укажите соединение и имя таблицы, используя синтаксис «точка»:unique:users

'email' => 'unique:connection.users,email_address'

Принудительное уникальное правило игнорирования заданного идентификатора:

Иногда вы можете игнорировать данный идентификатор во время уникальной проверки. Например, рассмотрим экран «Обновить профиль», который включает имя пользователя, адрес электронной почты и местоположение. Возможно, вы захотите убедиться, что адрес электронной почты является уникальным. Однако, если пользователь изменяет только поле имени, а не поле электронной почты, вы не хотите, чтобы выдавалась ошибка проверки, поскольку пользователь уже является владельцем адреса электронной почты.

Чтобы поручить валидатору игнорировать идентификатор пользователя, мы будем использовать Ruleкласс для свободного определения правила. В этом примере мы также указываем правила проверки в виде массива вместо использования |символа для разделения правил:

use IlluminateValidationRule;

Validator::make($data, [
    'email' => [
        'required',
        Rule::unique('users')->ignore($user->id),
    ],
]);

Вы никогда не должны передавать какой-либо пользовательский ввод запроса в ignoreметод. Вместо этого вы должны передавать только сгенерированный системой уникальный идентификатор, такой как идентификатор с автоматическим увеличением или UUID, из экземпляра модели Eloquent. В противном случае ваше приложение будет уязвимо для атаки SQL-инъекцией.

Вместо того, чтобы передавать значение ключа модели в ignoreметод, вы можете передать весь экземпляр модели. Laravel автоматически извлечет ключ из модели:

Rule::unique('users')->ignore($user)

Если ваша таблица использует имя столбца первичного ключа, отличное от id, вы можете указать имя столбца при вызове ignoreметода:

Rule::unique('users')->ignore($user->id, 'user_id')

По умолчанию uniqueправило проверяет уникальность столбца, совпадающего с именем проверяемого атрибута. Однако вы можете передать другое имя столбца в качестве второго аргумента uniqueметода:

Rule::unique('users', 'email_address')->ignore($user->id),

Добавление дополнительных предложений Where:

Вы также можете указать дополнительные ограничения запроса, настроив запрос с помощью whereметода. Например, давайте добавим ограничение , которое проверяет account_idIS 1:

'email' => Rule::unique('users')->where(function ($query) {
    return $query->where('account_id', 1);
})

url​​​​​​​

Проверяемое поле должно быть действительным URL.

uuid​​​​​​​

Проверяемое поле должно быть действительным универсальным уникальным идентификатором (UUID) RFC 4122 (версия 1, 3, 4 или 5).

Условия добавления правил

Проверка при наличии

В некоторых ситуациях вам может потребоваться выполнить проверки правильности для поля, только если это поле присутствует во входном массиве. Чтобы быстро это сделать, добавьте sometimesправило в список правил:

$v = Validator::make($data, [
    'email' => 'sometimes|required|email',
]);

В приведенном выше примере emailполе будет проверено, только если оно присутствует в $dataмассиве.

Если вы пытаетесь проверить поле, которое всегда должно присутствовать, но может быть пустым, ознакомьтесь с этим примечанием к дополнительным полям

Комплексная условная проверка

Иногда вы можете захотеть добавить правила проверки, основанные на более сложной условной логике. Например, вам может потребоваться указать данное поле только в том случае, если другое поле имеет значение больше 100. Или вам может потребоваться, чтобы два поля имели заданное значение только при наличии другого поля. Добавление этих правил проверки не должно быть проблемой. Сначала создайте Validatorэкземпляр со своими статическими правилами,которые никогда не меняются:

$v = Validator::make($data, [
    'email' => 'required|email',
    'games' => 'required|numeric',
]);

Давайте предположим, что наше веб-приложение предназначено для коллекционеров игр. Если коллекционер игр регистрируется в нашем приложении и им принадлежит более 100 игр, мы хотим, чтобы они объяснили, почему у них так много игр. Например, возможно, они управляют магазином перепродажи игр, или, возможно, им просто нравится коллекционировать. Чтобы условно добавить это требование, мы можем использовать sometimesметод в Validatorэкземпляре.

$v->sometimes('reason', 'required|max:500', function ($input) {
    return $input->games >= 100;
});

Первым аргументом, переданным sometimesметоду, является имя поля, которое мы условно проверяем. Второй аргумент — это правила, которые мы хотим добавить. Если Closureпередано в качестве третьего аргумента true, правила будут добавлены. Этот метод позволяет легко создавать сложные условные проверки. Вы можете даже добавить условные проверки для нескольких полей одновременно:

$v->sometimes(['reason', 'cost'], 'required', function ($input) {
    return $input->games >= 100;
});

$inputПараметр , переданный к вашему Closureбудет экземпляром и может использоваться для доступа к вашему вводу и файлам.IlluminateSupportFluent

Проверка массивов

Проверка полей ввода на основе массива не должна быть проблемой. Вы можете использовать «точечную нотацию» для проверки атрибутов в массиве. Например, если входящий HTTP-запрос содержит поле, вы можете проверить его следующим образом:photos[profile]

$validator = Validator::make($request->all(), [
    'photos.profile' => 'required|image',
]);

Вы также можете проверить каждый элемент массива. Например, чтобы проверить, что каждое электронное письмо в данном поле ввода массива уникально, вы можете сделать следующее:

$validator = Validator::make($request->all(), [
    'person.*.email' => 'email|unique:users',
    'person.*.first_name' => 'required_with:person.*.last_name',
]);

Аналогичным образом, вы можете использовать этот *символ при указании ваших сообщений проверки в ваших языковых файлах, что позволяет без труда использовать одно сообщение проверки для полей на основе массива:

'custom' => [
    'person.*.email' => [
        'unique' => 'Each person must have a unique e-mail address',
    ]
],

Пользовательские правила проверки

Использование объектов правил

Laravel предлагает множество полезных правил проверки; тем не менее, вы можете указать свои собственные. Одним из способов регистрации пользовательских правил проверки является использование объектов правил. Чтобы создать новый объект правила, вы можете использовать команду Artisan. Давайте использовать эту команду для генерации правила, которое проверяет строку в верхнем регистре. Laravel поместит новое правило в каталог:make:ruleapp/Rules

php artisan make:rule Uppercase

Как только правило было создано, мы готовы определить его поведение. Объект правила содержит два метода: passesи messagepassesМетод получает значение атрибута и имя, и он должен возвращать trueили в falseзависимости от того, является ли или нет значение атрибута. messageМетод должен возвращать сообщение об ошибке проверки , которая должна использоваться при сбое проверки:

<?php

namespace AppRules;

use IlluminateContractsValidationRule;

class Uppercase implements Rule
{
    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        return strtoupper($value) === $value;
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'The :attribute must be uppercase.';
    }
}

Вы можете вызвать transпомощника из вашего messageметода, если хотите вернуть сообщение об ошибке из ваших файлов перевода:

/**
 * Get the validation error message.
 *
 * @return string
 */
public function message()
{
    return trans('validation.uppercase');
}

Как только правило было определено, вы можете присоединить его к валидатору, передав экземпляр объекта правила с другими вашими правилами валидации:

use AppRulesUppercase;

$request->validate([
    'name' => ['required', 'string', new Uppercase],
]);

Использование замыканий

Если вам требуется функциональность настраиваемого правила только один раз в приложении, вы можете использовать Closure вместо объекта правила. Замыкание получает имя атрибута, значение атрибута и $failобратный вызов, который должен быть вызван в случае сбоя проверки:

$validator = Validator::make($request->all(), [
    'title' => [
        'required',
        'max:255',
        function ($attribute, $value, $fail) {
            if ($value === 'foo') {
                $fail($attribute.' is invalid.');
            }
        },
    ],
]);

Использование расширений

Другой метод регистрации пользовательских правил проверки — использование extendметода на Validator фасаде . Давайте использовать этот метод в сервис-провайдере для регистрации пользовательского правила проверки:

<?php

namespace AppProviders;

use IlluminateSupportServiceProvider;
use IlluminateSupportFacadesValidator;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Validator::extend('foo', function ($attribute, $value, $parameters, $validator) {
            return $value == 'foo';
        });
    }
}

Пользовательский валидатор Closure получает четыре аргумента: имя $attributeпроверяемого $valueобъекта, атрибута, массив, $parametersпередаваемый правилу, и Validatorэкземпляр.

Вы также можете передать класс и метод в extendметод вместо Closure:

Validator::extend('foo', 'FooValidator@validate');

Определение сообщения об ошибке

Вам также необходимо определить сообщение об ошибке для вашего пользовательского правила. Это можно сделать либо с помощью встроенного пользовательского массива сообщений, либо добавив запись в файл языка проверки. Это сообщение должно быть помещено в первый уровень массива, а не в customмассив, который предназначен только для сообщений об ошибках, относящихся к атрибуту:

"foo" => "Your input was invalid!",

"accepted" => "The :attribute must be accepted.",

// The rest of the validation error messages...

При создании пользовательского правила проверки иногда может потребоваться определить пользовательские замены заполнителей для сообщений об ошибках. Вы можете сделать это, создав пользовательский Validator, как описано выше, затем вызвав replacerметод на Validatorфасаде. Вы можете сделать это в рамках bootметода поставщика услуг :

/**
 * Bootstrap any application services.
 *
 * @return void
 */
public function boot()
{
    Validator::extend(...);

    Validator::replacer('foo', function ($message, $attribute, $rule, $parameters) {
        return str_replace(...);
    });
}

Неявные расширения

По умолчанию, когда проверяемый атрибут отсутствует или содержит пустую строку, обычные правила проверки, включая пользовательские расширения, не запускаются. Например, unique правило не будет запущено для пустой строки:

$rules = ['name' => 'unique:users,name'];

$input = ['name' => ''];

Validator::make($input, $rules)->passes(); // true

Чтобы правило запускалось, даже если атрибут пуст, правило должно подразумевать, что атрибут является обязательным. Чтобы создать такое «неявное» расширение, используйте метод:Validator::extendImplicit()

Validator::extendImplicit('foo', function ($attribute, $value, $parameters, $validator) {
    return $value == 'foo';
});

«Неявное» расширение подразумевает, что атрибут является обязательным. Независимо от того, действительно ли он аннулирует отсутствующий или пустой атрибут, зависит от вас.

As per 2019 Laravel 5.8 and above to get all the error messages from the validator is as easy as this:

// create the validator and make a validation here...
if ($validator->fails()) {
    $fieldsWithErrorMessagesArray = $validator->messages()->get('*');
}

You will get the array of arrays of the fields’ names and error messages. Something like this:

[
    'price'=>
        [ 
            0 => 'Price must be integer',
            1 => 'Price must be greater than 0'
        ]
    'password' => [
        [
            0 => 'Password is required'
        ]
    ]
    
]

You can use other validation messages getters that IlluminateSupportMessageBag class provides (it is actually the object type that $validator->messages() above returns).

Message Bag Error Messages Additional Helpers

Go to your_laravel_project_dir/vendor/illuminate/support/MessageBag.php and find some useful methods like keys, has, hasAny, first, all, isEmpty etc. that you may need while checking for particular validation errors and customizing HTTP response messages.

It is easy to understand what they do by the look at the source code. Here is the Laravel 5.8 API reference though probably less useful than the source code.

Краткий пример

Пример валидации формы и вывод сообщений об ошибках для пользователя.

Определение роутов

Создадим роуты в файле routes/web.php:

Route::get('post/create', 'PostController@create');

Route::post('post', 'PostController@store');

Роут GET отображает форму для создания нового поста в блоге, POST будет сохранять новую запись в базе данных.

Создание контроллера

Контроллер, который обрабатывает эти роуты. Метод store пока остался пустым:

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;
use AppHttpControllersController;

class PostController extends Controller
{
    /**
     * Показать форму для создания новой записи в блоге.
     *
     * @return Response
     */
    public function create()
    {
        return view('post.create');
    }

    /**
     * Хранить новую запись в блоге.
     *
     * @param  Request  $request
     * @return Response
     */
    public function store(Request $request)
    {
        // Validate and store the blog post...
    }
}

Написание логики валидации

Заполняем метод store валидацией при создания нового поста. Если проанализировать базовый контроллер (AppHttpControllersController), видно, что он включает в себя трейт ValidatesRequests, который обеспечивает все контроллеры удобным методом validate.

Метод validate принимает два параметра экземпляр HTTP запроса и правила валидации. Если все правила не нарушены, код будет выполняться далее. Однако, если проверка не пройдена, будет выброшено исключение и сообщение об ошибке автоматически отправится обратно пользователю. В HTTP запросе ответ будет перенаправлен обратно с заполненными flash-переменными, в то время как на AJAX запрос отправится JSON.

Для понимания метода validate, пример store:

/**
 * Store a new blog post.
 *
 * @param  Request  $request
 * @return Response
 */
public function store(Request $request)
{
    $this->validate($request, [
        'title' => 'required|unique:posts|max:255',
        'body' => 'required',
    ]);

    // The blog post is valid, store in database...
}

Остановка после первой неудачной проверки

Если нужно остановить выполнение остальных правил после первой неудачной проверки. Для этого используется атрибут bail:

$this->validate($request, [
    'title' => 'bail|unique:posts|max:255',
    'body' => 'required',
]);

В этом примере, если для атрибута title не выполняется правило required, следующие правило unique проверяться не будет.

Проверка вложенных атрибутах (массив)

Если данные HTTP запроса содержат «вложенные» параметры, можно указать их, используя синтаксис с точкой:

$this->validate($request, [
    'title' => 'required|unique:posts|max:255',
    'author.name' => 'required',
    'author.description' => 'required',
]);

Отображение ошибок валидации

В примере пользователь будет перенаправлен в метод create контроллера и можно отобразить сообщения об ошибках в шаблоне:

<!-- /resources/views/post/create.blade.php -->

<h1>Create Post</h1>

@if ($errors->any())
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

<!-- Create Post Form -->

Дополнительные поля

По умолчанию в Laravel включены глобальные посредники TrimStrings и mptConvertEyStringsToNull. Они перечислены в свойстве $middleware класса AppHttpKernel. Из-за этого нужно часто помечать дополнительные поля как nullable, если не нужно, чтобы валидатор считал не действительным значение null. Например:

$this->validate($request, [
    'title' => 'required|unique:posts|max:255',
    'body' => 'required',
    'publish_at' => 'nullable|date',
]);

В этом примере указано что поле publish_at может быть null или должно содержать дату. Если модификатор nullable не добавляется в правило, проверяющий элемент будет рассматривать null как недопустимую дату.

Настройка формата вывода ошибок валидации

Для настройки вывода ошибок валидации, которые будут во flash-переменных после нарушений правил, нужно переопределить метод formatValidationErrors в базовом контроллере и подключить класс IlluminateContractsValidationValidator:

<?php

namespace AppHttpControllers;

use IlluminateFoundationBusDispatchesJobs;
use IlluminateContractsValidationValidator;
use IlluminateRoutingController as BaseController;
use IlluminateFoundationValidationValidatesRequests;

abstract class Controller extends BaseController
{
    use DispatchesJobs, ValidatesRequests;

    /**
     * {@inheritdoc}
     */
    protected function formatValidationErrors(Validator $validator)
    {
        return $validator->errors()->all();
    }
}

AJAX запросы и валидация

При использовании метода validate во время запроса AJAX, Laravel не будет генерировать ответ с перенаправлением. Вместо этого Laravel генерирует ответ с JSON данными, содержащий в себе все ошибки проверки. Этот ответ будет отправлен с кодом состояния HTTP 422.

Валидация form request

Создание Form Request

# php artisan make:request StoreBlogPost

Сгенерированный класс будет размещен в каталоге app/Http/Requests

Для проверки используется метод rules:

/**
 * Получить правила валидации, применимые к запросу.
 *
 * @return array
 */
public function rules()
{
    return [
        'title' => 'required|unique:posts|max:255',
        'body' => 'required',
    ];
}

Для проверки валидации необходимо в методе контроллера для входящей переменной указать класс как тип переменной

/**
 * Store the incoming blog post.
 *
 * @param  StoreBlogPost  $request
 * @return Response
 */
public function store(StoreBlogPost $request)
{
    // The incoming request is valid...
}

Если проверка не пройдена, то при традиционном запросе ошибки будут записываться в сессию и будут доступны в шаблонах, иначе, если запрос был AJAX, HTTP-ответ с кодом 422 будет возвращен пользователю, включая JSON с ошибками валидации.

Добавление хуков в Form Request

Если необходимо добавить хук «after» в Form Requests, можно использовать метод withValidator. Этот метод получает полностью сформированный валидатор, позволяя вызвать любой из его методов, прежде чем фактически применяются правила:

/**
 * Настройка экземпляра валидатора.
 *
 * @param  IlluminateValidationValidator  $validator
 * @return void
 */
public function withValidator($validator)
{
    $validator->after(function ($validator) {
        if ($this->somethingElseIsInvalid()) {
            $validator->errors()->add('field', 'Something is wrong with this field!');
        }
    });
}

Авторизация Form Request

Класс Form Request содержит в себе метод authorize. В этом методе можно проверить, имеет ли аутентифицированный пользователь права на выполнение данного запроса. Например, можно проверить, есть ли у пользователя право для добавления комментариев в блог:

/**
 * Определить авторизован ли пользователь делать такой запрос.
 *
 * @return bool
 */
public function authorize()
{
    $comment = Comment::find($this->route('comment'));

    return $comment && $this->user()->can('update', $comment);
}

Form Request расширяет базовый класс Request, и можно использовать метод user, чтобы получить доступ к текущему пользователю. Вызов метода route предоставляет доступ к параметрам URI, определенным в роуте (в приведенном ниже примере это {comment}):

Route::post('comment/{comment}');

Если метод authorize возвращает false, автоматически генерируется ответ с кодом 403 и метод контроллера не выполняется.

Если же логика авторизации организована в другом месте приложения, просто достаточно вернуть true из метода authorize:

/**
 * Определить авторизован ли пользователь делать такой запрос.
 *
 * @return bool
 */
public function authorize()
{
    return true;
}

Настройка формата вывода ошибок

Если нужно настроить формат вывода ошибок валидации, которые будут заполнять flash-переменные при неудачном выполнении, необходимо переопредилить метод formatErrors в базовом request (AppHttpRequestsRequest). Должен быт подключен класс IlluminateContractsValidationValidator:

/**
 * {@inheritdoc}
 */
protected function formatErrors(Validator $validator)
{
    return $validator->errors()->all();
}

Настройка сообщений об ошибках

Для кастомизации сообщений об ошибках, используется в form request метод messages. Этот метод должен возвращать массив атрибутов/правил и их соответствующие сообщения об ошибках:

/**
 * Get the error messages for the defined validation rules.
 *
 * @return array
 */
public function messages()
{
    return [
        'title.required' => 'A title is required',
        'body.required'  => 'A message is required',
    ];
}

Создание валидаторов вручную

<?php

namespace AppHttpControllers;

use Validator;
use IlluminateHttpRequest;
use AppHttpControllersController;

class PostController extends Controller
{
    /**
     * Store a new blog post.
     *
     * @param  Request  $request
     * @return Response
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'title' => 'required|unique:posts|max:255',
            'body' => 'required',
        ]);

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

        // Store the blog post...
    }
}

Первый аргумент, передаваемый в метод make, получает данные для проверки. Вторым аргументом идут правилами проверки, которые должны применяться к данным.

После проверки, если валидация не будет пройдена, можно использовать метод withErrors для загрузки ошибок во flash-переменные. При использовании этого метода переменная $errors будет автоматически передаваться в макеты, после перенаправления, что позволяет легко отображать данные пользователю. Метод withErrors принимает экземпляр валидатора и MessageBag или простой массив.

Автоматическое перенаправление

Validator::make($request->all(), [
    'title' => 'required|unique:posts|max:255',
    'body' => 'required',
])->validate();

MessageBag

Если есть несколько форм на одной страницы, которые необходимо провалидировать, понадобится MessageBag — он позволяет получать сообщения об ошибках для определенной формы. Нужно передайть имя в качестве второго аргумента withErrors:

return redirect('register')
            ->withErrors($validator, 'login');

Затем можно получить доступ к именованному экземпляру MessageBag из переменной $errors:

{{ $errors->login->first('email') }}

Хук после валидации

Валидатор также позволяет использовать функции обратного вызова после завершения всех проверок. Это позволяет легко выполнять дальнейшие проверки и даже добавить больше сообщений об ошибках в коллекции сообщений. Для начала работы нужно использовать метод after в экземпляре валидатора:

$validator = Validator::make(...);

$validator->after(function ($validator) {
    if ($this->somethingElseIsInvalid()) {
        $validator->errors()->add('field', 'Something is wrong with this field!');
    }
});

if ($validator->fails()) {
    //
}

Работа с сообщениями об ошибках

После вызова метода errors в экземпляре валидатора, получаем экземпляр IlluminateSupportMessageBag, который имеет целый ряд удобных методов для работы с сообщениями об ошибках. Переменная $errors, которая автоматически становится доступной для всех макетов, также является экземпляром класса MessageBag.

Извлечение первого для поля сообщения об ошибке

$errors = $validator->errors();

echo $errors->first('email');

Извлечение всех сообщений об ошибках для одного поля

foreach ($errors->get('email') as $message) {
    //
}

Если выполняется проверка поля формы с массивом, можно получить все сообщения для каждого из элементов массива с помощью символа *:

foreach ($errors->get('attachments.*') as $message) {
    //
}

Получение всех сообщений об ошибках для всех полей

foreach ($errors->all() as $message) {
    //
}

Определить наличие сообщения для определенного поля

if ($errors->has('email')) {
    //
}

Пользовательские сообщения об ошибках

При необходимости, можно использовать свои сообщения об ошибках вместо значений по умолчанию. Существует несколько способов для указания кастомных сообщений. Можно передать сообщения в качестве третьего аргумента в метод Validator::make:

$messages = [
    'required' => 'The :attribute field is required.',
];

$validator = Validator::make($input, $rules, $messages);

В этом примере :attributeбудет заменен на имя проверяемого поля. Можено использовать и другие строки-переменные. Пример:

$messages = [
    'same'    => 'The :attribute and :other must match.',
    'size'    => 'The :attribute must be exactly :size.',
    'between' => 'The :attribute must be between :min - :max.',
    'in'      => 'The :attribute must be one of the following types: :values',
];

Указание пользовательского сообщения для заданного атрибута

$messages = [
    'email.required' => 'We need to know your e-mail address!',
];

Указание собственных сообщений в файлах локализации

Также можно определять сообщения в файле локализации вместо того, чтобы передавать их в валидатор напрямую. Для этого нужно добавить сообщения в массив custom файла локализации resources/lang/xx/validation.php.

'custom' => [
    'email' => [
        'required' => 'We need to know your e-mail address!',
    ],
],

Указание пользовательских атрибутов в файлах локализации

Если необходимо, чтобы :attribute был заменен на кастомное имя, можно указать в массиве attributes файле локализации resources/lang/xx/validation.php:

'attributes' => [
    'email' => 'email address',
],

Доступные правила валидации

accepted — поле должно быть в значении yes, on или 1. Это полезно для проверки принятия правил и лицензий.

active_url — поле должно иметь действительную A или AAAA DNS-запись согласно функции PHP dns_get_record.

after:date — поле проверки должно быть после date. Строки приводятся к датам функцией strtotime:

'start_date' => 'required|date|after:tomorrow'

Вместо того чтобы приводить строки к датам, вы можете указать другое поле для сравнения даты:

'finish_date' => 'required|date|after:start_date'

after_or_equal:date — поле проверки должно быть после или равно date. Для получения дополнительной информации смотрите правило after

alpha — поле должно содержать только алфавитные символы.

alpha_dash — поле можно содержать только алфавитные символы, цифры, знаки подчёркивания _ и дефисы -.

alpha_num — поле можно содержать только алфавитные символы и цифры.

array — поле должно быть PHP-массивом.

before:date — поле должно быть датой более ранней, чем заданная дата. Строки приводятся к датам функцией strtotime.

before_or_equal:date — поле должно быть более ранней или равной заданной дате. Строки приводятся к датам функцией strtotime.

between:min,max — поле должно быть числом в диапазоне от min до max. Размеры строк, чисел и файлов трактуются аналогично правилу size.

boolean — поле должно быть логическим (булевым). Разрешенные значения: true, false, 1, 0, «1», и «0».

confirmed — значение поля должно соответствовать значению поля с этим именем, плюс foo_confirmation. Например, если проверяется поле password, то на вход должно быть передано совпадающее по значению поле password_confirmation.

date — поле должно быть правильной датой в соответствии с PHP функцией strtotime.

date_format:format — поле должно соответствовать заданному формату. Необходимо использовать функцию date или date_format при проверке поля, но не обе.

different:field — значение проверяемого поля должно отличаться от значения поля field.

digits:value — поле должно быть числовым и иметь точную длину значения.

digits_between:min,max — длина значения поля проверки должна быть между min и max.

dimensions — файл изображения должен иметь ограничения согласно параметрам:

'avatar' => 'dimensions:min_width=100,min_height=200'

Доступные ограничения: _min_width_, _max_width_, _min_height_, _max_height_, width, height, ratio.
Ограничение ratio должно быть представлено как ширина к высоте. Это может быть обыкновенная (3/2) или десятичная (1.5) дробь:

'avatar' => 'dimensions:ratio=3/2'

Поскольку это правило требует несколько аргументов, вы можете использовать метод Rule::dimensions:

use IlluminateValidationRule;

Validator::make($data, [
    'avatar' => [
        'required',
        Rule::dimensions()->maxWidth(1000)->maxHeight(500)->ratio(3 / 2),
    ],
]);

distinct — при работе с массивами, поле не должно иметь повторяющихся значений.

'foo.*.id' => 'distinct'

email — поле должно быть корректным адресом e-mail.

exists:table,column — поле должно существовать в указанной таблице базы данных.
базовое использование правила Exists

'state' => 'exists:states'

указание пользовательского названия столбца

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

Иногда может потребоваться подключение к базе данных и использование в запросе exists, этого можно добиться путем добавления к соединению название таблицы, используя синтаксис с точкой:

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

Если бы вы хотите модифицировать запрос, можно использовать класс Rule, в данном примере мы будем использовать массив вместо знака |:

use IlluminateValidationRule;

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

file — поле должно быть успешно загруженным файлом.

filled — поле не должно быть пустым.

image — загруженный файл должен быть в формате jpeg, png, bmp, gif или svg.

in:foo,bar,… -значение поля должно быть одним из перечисленных. Поскольку это правило иногда вынуждает вас использовать функцию implode, для этого случая есть метод Rule::in:

use IlluminateValidationRule;

Validator::make($data, [
    'zones' => [
        'required',
        Rule::in(['first-zone', 'second-zone']),
    ],
]);

in_array:anotherfield — в массиве должны существовать значения anotherfield.

integer — поле должно иметь корректное целочисленное значение.

ip — поле должно быть корректным IP-адресом.

ipv4 — поле должно быть IPv4-адресом.

ipv6 — поле должно быть IPv6-адресом.

json — поле должно быть валидной строкой JSON.

max:value — значение поля должно быть меньше или равно value. Размеры строк, чисел и файлов трактуются аналогично правилу size.

mimetypes:text/plain,… — MIME-тип загруженного файла должен быть одним из перечисленных:

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

Чтобы определить MIME-тип загруженного файла, фреймворк будет читать содержимое и пытаться угадать MIME-тип, который может отличаться от того, что указал пользователь.

mimes:foo,bar,… — MIME-тип загруженного файла должен быть одним из перечисленных.
Основное использование MIME-правила

'photo' => 'mimes:jpeg,bmp,png'

Даже если необходимо только указать расширение, это правило проверяет MIME-тип файла, читая содержимое файла и пытаясь угадать его.
Полный список MIME-типов и соответствующие им расширения можно найти в: https://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types

min:value — Значение поля должно быть больше value. Размеры строк, чисел и файлов трактуются аналогично правилу size.

nullable — поле может быть равно null. Это особенно полезно при проверке примитивов, такие как строки и целые числа, которые могут содержать null значения.

not_in:foo,bar,… — поле не должно быть включено в заданный список значений. Метод Rule::notIn можно использовать для конструирования этого правила:

use IlluminateValidationRule;

Validator::make($data, [
    'toppings' => [
        'required',
        Rule::notIn(['sprinkles', 'cherries']),
    ],
]);

numeric — поле должно иметь корректное числовое или дробное значение.

present — поле для проверки должно присутствовать во входных данных, но может быть пустым.

regex:pattern — поле должно соответствовать заданному регулярному выражению.
Примечание: Для использования regex может быть необходимо определить правила в виде массива вместо использования разделителя, особенно если регулярное выражение содержит символ разделителя.

required — проверяемое поле должно иметь непустое значение. Поле считается пустым, если одно из следующих значений верно:

  • если значение равно null.
  • если значение — пустая строка.
  • если значение является пустым массивом или пустым объектом Countable.
  • если значение это загруженный файл без пути.

required_if:anotherfield,value,… — поле должно присутствовать и не быть пустым, если anotherfield равно любому value.

required_unless:anotherfield,value,… — поле должно присутствовать и не быть пустым, за исключением случая, когда anotherfield равно любому value.

required_with:foo,bar,… — проверяемое поле должно иметь непустое значение, но только если присутствует хотя бы одно из перечисленных полей (foo, bar и т.д.).

required_with_all:foo,bar,… — проверяемое поле должно иметь непустое значение, но только если присутствуют все перечисленные поля (foo, bar и т.д.).

required_without:foo,bar,… — проверяемое поле должно иметь непустое значение, но только если не присутствует хотя бы одно из перечисленных полей (foo, bar и т.д.).

required_without_all:foo,bar,… — проверяемое поле должно иметь непустое значение, но только если не присутствуют все перечисленные поля (foo, bar и т.д.).

same:field — поле должно иметь то же значение, что и поле field.

size:value — поле должно иметь совпадающий с value размер. Для строковых данных value соответствует количество символов, для массива size соответствует количеству элементов массива, для чисел — число, для файлов — размер в килобайтах.

string — поле должно быть строкой. Если вы хотите, чтобы поле было null, следует доолнитель указать это полю правило nullable.

timezone — поле должно содержать идентификатор часового пояса (таймзоны), один из перечисленных в php-функции timezone_identifiers_list.

unique:table,column,except,idColumn — значение поля должно быть уникальным в заданной таблице базы данных. Если column не указано, то будет использовано имя поля.
указание пользовательского названия столбца:

'email' => 'unique:users,email_address'

пользовательское подключение к БД
иногда может понадобиться установить собственное соединение с базой данных, как замечено выше, параметр unique:users, будет использовать соединение по умолчанию. Чтобы переопределить это, нужно указать подключение и имя таблицы через синтаксис с точкой:

'email' => 'unique:connection.users,email_address'

игнорирование ID при проверке на уникальность:
иногда потребуется игнорировать ID при проверке на уникальность. Например, рассмотрим обновление профиля пользователя, который включает в себя имя пользователя, адрес электронной почты и местоположение. Конечно, вы хотите убедиться, что адрес электронной почты является уникальным. Однако, если пользователь изменяет только имя и не изменяет электронную почту, нам не требуется вывод ошибки, но тем не менее возникнет исключение, поскольку пользователь уже является владельцем адреса электронной почты.

Для того, чтобы игнорировать ID пользователя, мы будем использовать класс Rule который позволяет гибко строить наши правила в таком случае. В примере, мы укажем правила в качестве массива вместо | символа-разделителя:

use IlluminateValidationRule;

Validator::make($data, [
    'email' => [
        'required',
        Rule::unique('users')->ignore($user->id),
    ],
]);

Если таблица использует имя столбца первичного ключа помимо id, можно указать имя столбца при вызове метода ignore:

'email' => Rule::unique('users')->ignore($user->id, 'user_id')

Добавление дополнительных условий Where:

Вы также можете указать дополнительные условия, используя метод where. Например, давайте добавим ограничение, которое проверяет, что account_id равно 1:

'email' => Rule::unique('users')->where(function ($query) {
    $query->where('account_id', 1);
})

url — поле должно быть корректным URL.

Добавление правил с условиями

Валидация при наличии поля

Иногда нужно проверить некое поле только тогда, когда оно присутствует во входных данных. Для этого добавьте правило sometimes:

$v = Validator::make($data, [
    'email' => 'sometimes|required|email',
]);

В примере выше для поля email будет запущена валидация только, когда оно присутствует в массиве $data.

Сложная составная проверка

Иногда возникает необходимость добавить правила с более сложной логикой проверки. Например, потребовать поле, только если другое поле имеет значение большее, чем 100. Или понадобится два поля, когда другое поле присутствует. Добавление этих правил не должно вызывать затруднения. Создается экземпляр Validator с постоянными правилами, которые никогда не изменятся:

$v = Validator::make($data, [
    'email' => 'required|email',
    'games' => 'required|numeric',
]);

Предположим, что веб-приложение для коллекционеров игр. Если коллекционер регистрирует в приложении игру и он владеет больше чем 100 играми в данный момент, нужно, чтобы он объяснил, почему он владеет таким количеством игр. Возможно, он управляет магазином игр, или возможно, он просто любит их собирать. Чтобы добавить это требование, можно использовать метод sometimes в экземпляре валидатора:

$v->sometimes('reason', 'required|max:500', function ($input) {
    return $input->games >= 100;
});

Первый аргумент, переданный в метод sometimes это имя поля, которое условно проверяется. Второй аргумент — правила, которые нужно добавить. Если анонимная функция передается как третий аргумент, и возвращает значение true, то правила будут добавлены. Этот метод универсален для того, чтобы строить целый комплекс условных проверок. Можно даже добавить условные проверки на нескольких полях одновременно:

$v->sometimes(['reason', 'cost'], 'required', function ($input) {
    return $input->games >= 100;
});

img

Параметр $input переданный в анонимную функцию, будет экземпляром IlluminateSupportFluent и может быть использован для доступа к полям и файлам.

Валидация массивов

Чтобы проверить, что каждая последующая электронная почта является уникальной, вы можете сделать следующее:

$validator = Validator::make($request->all(), [
    'photos.profile' => 'required|image',
]);

* — использовать одно сообщение для проверки массива полей:

$validator = Validator::make($request->all(), [
    'person.*.email' => 'email|unique:users',
    'person.*.first_name' => 'required_with:person.*.last_name',
]);

Можно использовать символ * при указании сообщений валидации в языковых файлах, значительно упрощая использование одного сообщения валидации для полей, основанных на массивах:

'custom' => [
    'person.*.email' => [
        'unique' => 'Each person must have a unique e-mail address',
    ]
],

Собственные правила валидации

Laravel предоставляет разнообразные и полезные правила для валидации. Однако, возможно, потребуется определить некоторые из своих собственных. Один из методов регистрации своих правил метод extend фасада Validator. Пример регистрации этого метода в сервис-провайдере:

<?php

namespace AppProviders;

use IlluminateSupportServiceProvider;
use IlluminateSupportFacadesValidator;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Предварительная загрузка любых сервисов приложения.
     *
     * @return void
     */
    public function boot()
    {
        Validator::extend('foo', function ($attribute, $value, $parameters, $validator) {
            return $value == 'foo';
        });
    }

    /**
     * Регистрация нового сервис-провайдера.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

Анонимная функция получает четыре аргумента: имя проверяемого поля ($attribute), значение поля ($value), массив дополнительных параметров ($parameters) и экземпляр валидатора ($validator).

Класс и метод также можно передать методу extend вместо анонимной функции:

Validator::extend('foo', 'FooValidator@validate');

Определение сообщения об ошибки

Правила сообщений об ошибке можно передавть в виде массива строк в валидатор, либо добавив в файл локализации. Это сообщение должно помещаться на первом уровне массива, но не в массиве custom, который появляется только для сообщения об ошибке конкретного атрибута:

"foo" => "Your input was invalid!",

"accepted" => "The :attribute must be accepted.",

// The rest of the validation error messages...

При создании своих правил проверки, может потребоваться определить места замены для сообщений об ошибках. Можно сделать это, реализовав через метод replacer в фасаде Validator. Действие необходимо определить внутри метода boot сервис-провайдера:

/**
 * Bootstrap any application services.
 *
 * @return void
 */
public function boot()
{
    Validator::extend(...);

    Validator::replacer('foo', function ($message, $attribute, $rule, $parameters) {
        return str_replace(...);
    });
}

Скрытые расширения

По умолчанию, когда проверяемый атрибут отсутствует или содержит пустое значение, как в правиле required, валидация не выполняется, в том числе и для расширений. Например, unique не будет выполнено для значения null:

$rules = ['name' => 'unique'];

$input = ['name' => null];

Validator::make($input, $rules)->passes(); // true

Правило должно подразумевать, что атрибут обязателен, даже, если он пуст. Для создания «скрытых» расширений используйте метод Validator::extendImplicit():

Validator::extendImplicit('foo', function ($attribute, $value, $parameters, $validator) {
    return $value == 'foo';
});

img

«Скрытое» расширение лишь подразумевает, что атрибут является обязательным.

Validation

  • Introduction
  • Validation Quickstart
    • Defining The Routes
    • Creating The Controller
    • Writing The Validation Logic
    • Displaying The Validation Errors
    • A Note On Optional Fields
  • Form Request Validation
    • Creating Form Requests
    • Authorizing Form Requests
    • Customizing The Error Messages
    • Customizing The Validation Attributes
    • Prepare Input For Validation
  • Manually Creating Validators
    • Automatic Redirection
    • Named Error Bags
    • After Validation Hook
  • Working With Error Messages
    • Custom Error Messages
  • Available Validation Rules
  • Conditionally Adding Rules
  • Validating Arrays
  • Custom Validation Rules
    • Using Rule Objects
    • Using Closures
    • Using Extensions
    • Implicit Extensions

Introduction

Laravel provides several different approaches to validate your application’s incoming data. By default, Laravel’s base controller class uses a ValidatesRequests trait which provides a convenient method to validate incoming HTTP request with a variety of powerful validation rules.

Validation Quickstart

To learn about Laravel’s powerful validation features, let’s look at a complete example of validating a form and displaying the error messages back to the user.

Defining The Routes

First, let’s assume we have the following routes defined in our routes/web.php file:

Route::get('post/create', 'PostController@create');

Route::post('post', 'PostController@store');

The GET route will display a form for the user to create a new blog post, while the POST route will store the new blog post in the database.

Creating The Controller

Next, let’s take a look at a simple controller that handles these routes. We’ll leave the store method empty for now:

<?php

namespace AppHttpControllers;

use AppHttpControllersController;
use IlluminateHttpRequest;

class PostController extends Controller
{
    /**
     * Show the form to create a new blog post.
     *
     * @return Response
     */
    public function create()
    {
        return view('post.create');
    }

    /**
     * Store a new blog post.
     *
     * @param  Request  $request
     * @return Response
     */
    public function store(Request $request)
    {
        // Validate and store the blog post...
    }
}

Writing The Validation Logic

Now we are ready to fill in our store method with the logic to validate the new blog post. To do this, we will use the validate method provided by the IlluminateHttpRequest object. If the validation rules pass, your code will keep executing normally; however, if validation fails, an exception will be thrown and the proper error response will automatically be sent back to the user. In the case of a traditional HTTP request, a redirect response will be generated, while a JSON response will be sent for AJAX requests.

To get a better understanding of the validate method, let’s jump back into the store method:

/**
 * Store a new blog post.
 *
 * @param  Request  $request
 * @return Response
 */
public function store(Request $request)
{
    $validatedData = $request->validate([
        'title' => 'required|unique:posts|max:255',
        'body' => 'required',
    ]);

    // The blog post is valid...
}

As you can see, we pass the desired validation rules into the validate method. Again, if the validation fails, the proper response will automatically be generated. If the validation passes, our controller will continue executing normally.

Alternatively, validation rules may be specified as arrays of rules instead of a single | delimited string:

$validatedData = $request->validate([
    'title' => ['required', 'unique:posts', 'max:255'],
    'body' => ['required'],
]);

If you would like to specify the error bag in which the error messages should be placed, you may use the validateWithBag method:

$request->validateWithBag('blog', [
    'title' => ['required', 'unique:posts', 'max:255'],
    'body' => ['required'],
]);

Stopping On First Validation Failure

Sometimes you may wish to stop running validation rules on an attribute after the first validation failure. To do so, assign the bail rule to the attribute:

$request->validate([
    'title' => 'bail|required|unique:posts|max:255',
    'body' => 'required',
]);

In this example, if the unique rule on the title attribute fails, the max rule will not be checked. Rules will be validated in the order they are assigned.

A Note On Nested Attributes

If your HTTP request contains «nested» parameters, you may specify them in your validation rules using «dot» syntax:

$request->validate([
    'title' => 'required|unique:posts|max:255',
    'author.name' => 'required',
    'author.description' => 'required',
]);

Displaying The Validation Errors

So, what if the incoming request parameters do not pass the given validation rules? As mentioned previously, Laravel will automatically redirect the user back to their previous location. In addition, all of the validation errors will automatically be flashed to the session.

Again, notice that we did not have to explicitly bind the error messages to the view in our GET route. This is because Laravel will check for errors in the session data, and automatically bind them to the view if they are available. The $errors variable will be an instance of IlluminateSupportMessageBag. For more information on working with this object, check out its documentation.

{tip} The $errors variable is bound to the view by the IlluminateViewMiddlewareShareErrorsFromSession middleware, which is provided by the web middleware group. When this middleware is applied an $errors variable will always be available in your views, allowing you to conveniently assume the $errors variable is always defined and can be safely used.

So, in our example, the user will be redirected to our controller’s create method when validation fails, allowing us to display the error messages in the view:

<!-- /resources/views/post/create.blade.php -->

<h1>Create Post</h1>

@if ($errors->any())
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

<!-- Create Post Form -->

The @error Directive

You may also use the @error Blade directive to quickly check if validation error messages exist for a given attribute. Within an @error directive, you may echo the $message variable to display the error message:

<!-- /resources/views/post/create.blade.php -->

<label for="title">Post Title</label>

<input id="title" type="text" class="@error('title') is-invalid @enderror">

@error('title')
    <div class="alert alert-danger">{{ $message }}</div>
@enderror

A Note On Optional Fields

By default, Laravel includes the TrimStrings and ConvertEmptyStringsToNull middleware in your application’s global middleware stack. These middleware are listed in the stack by the AppHttpKernel class. Because of this, you will often need to mark your «optional» request fields as nullable if you do not want the validator to consider null values as invalid. For example:

$request->validate([
    'title' => 'required|unique:posts|max:255',
    'body' => 'required',
    'publish_at' => 'nullable|date',
]);

In this example, we are specifying that the publish_at field may be either null or a valid date representation. If the nullable modifier is not added to the rule definition, the validator would consider null an invalid date.

AJAX Requests & Validation

In this example, we used a traditional form to send data to the application. However, many applications use AJAX requests. When using the validate method during an AJAX request, Laravel will not generate a redirect response. Instead, Laravel generates a JSON response containing all of the validation errors. This JSON response will be sent with a 422 HTTP status code.

Form Request Validation

Creating Form Requests

For more complex validation scenarios, you may wish to create a «form request». Form requests are custom request classes that contain validation logic. To create a form request class, use the make:request Artisan CLI command:

php artisan make:request StoreBlogPost

The generated class will be placed in the app/Http/Requests directory. If this directory does not exist, it will be created when you run the make:request command. Let’s add a few validation rules to the rules method:

/**
 * Get the validation rules that apply to the request.
 *
 * @return array
 */
public function rules()
{
    return [
        'title' => 'required|unique:posts|max:255',
        'body' => 'required',
    ];
}

{tip} You may type-hint any dependencies you need within the rules method’s signature. They will automatically be resolved via the Laravel service container.

So, how are the validation rules evaluated? All you need to do is type-hint the request on your controller method. The incoming form request is validated before the controller method is called, meaning you do not need to clutter your controller with any validation logic:

/**
 * Store the incoming blog post.
 *
 * @param  StoreBlogPost  $request
 * @return Response
 */
public function store(StoreBlogPost $request)
{
    // The incoming request is valid...

    // Retrieve the validated input data...
    $validated = $request->validated();
}

If validation fails, a redirect response will be generated to send the user back to their previous location. The errors will also be flashed to the session so they are available for display. If the request was an AJAX request, a HTTP response with a 422 status code will be returned to the user including a JSON representation of the validation errors.

Adding After Hooks To Form Requests

If you would like to add an «after» hook to a form request, you may use the withValidator method. This method receives the fully constructed validator, allowing you to call any of its methods before the validation rules are actually evaluated:

/**
 * Configure the validator instance.
 *
 * @param  IlluminateValidationValidator  $validator
 * @return void
 */
public function withValidator($validator)
{
    $validator->after(function ($validator) {
        if ($this->somethingElseIsInvalid()) {
            $validator->errors()->add('field', 'Something is wrong with this field!');
        }
    });
}

Authorizing Form Requests

The form request class also contains an authorize method. Within this method, you may check if the authenticated user actually has the authority to update a given resource. For example, you may determine if a user actually owns a blog comment they are attempting to update:

/**
 * Determine if the user is authorized to make this request.
 *
 * @return bool
 */
public function authorize()
{
    $comment = Comment::find($this->route('comment'));

    return $comment && $this->user()->can('update', $comment);
}

Since all form requests extend the base Laravel request class, we may use the user method to access the currently authenticated user. Also note the call to the route method in the example above. This method grants you access to the URI parameters defined on the route being called, such as the {comment} parameter in the example below:

Route::post('comment/{comment}');

If the authorize method returns false, a HTTP response with a 403 status code will automatically be returned and your controller method will not execute.

If you plan to have authorization logic in another part of your application, return true from the authorize method:

/**
 * Determine if the user is authorized to make this request.
 *
 * @return bool
 */
public function authorize()
{
    return true;
}

{tip} You may type-hint any dependencies you need within the authorize method’s signature. They will automatically be resolved via the Laravel service container.

Customizing The Error Messages

You may customize the error messages used by the form request by overriding the messages method. This method should return an array of attribute / rule pairs and their corresponding error messages:

/**
 * Get the error messages for the defined validation rules.
 *
 * @return array
 */
public function messages()
{
    return [
        'title.required' => 'A title is required',
        'body.required'  => 'A message is required',
    ];
}

Customizing The Validation Attributes

If you would like the :attribute portion of your validation message to be replaced with a custom attribute name, you may specify the custom names by overriding the attributes method. This method should return an array of attribute / name pairs:

/**
 * Get custom attributes for validator errors.
 *
 * @return array
 */
public function attributes()
{
    return [
        'email' => 'email address',
    ];
}

Prepare Input For Validation

If you need to sanitize any data from the request before you apply your validation rules, you can use the prepareForValidation method:

use IlluminateSupportStr;

/**
 * Prepare the data for validation.
 *
 * @return void
 */
protected function prepareForValidation()
{
    $this->merge([
        'slug' => Str::slug($this->slug),
    ]);
}

Manually Creating Validators

If you do not want to use the validate method on the request, you may create a validator instance manually using the Validator facade. The make method on the facade generates a new validator instance:

<?php

namespace AppHttpControllers;

use AppHttpControllersController;
use IlluminateHttpRequest;
use IlluminateSupportFacadesValidator;

class PostController extends Controller
{
    /**
     * Store a new blog post.
     *
     * @param  Request  $request
     * @return Response
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'title' => 'required|unique:posts|max:255',
            'body' => 'required',
        ]);

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

        // Store the blog post...
    }
}

The first argument passed to the make method is the data under validation. The second argument is the validation rules that should be applied to the data.

After checking if the request validation failed, you may use the withErrors method to flash the error messages to the session. When using this method, the $errors variable will automatically be shared with your views after redirection, allowing you to easily display them back to the user. The withErrors method accepts a validator, a MessageBag, or a PHP array.

Automatic Redirection

If you would like to create a validator instance manually but still take advantage of the automatic redirection offered by the request’s validate method, you may call the validate method on an existing validator instance. If validation fails, the user will automatically be redirected or, in the case of an AJAX request, a JSON response will be returned:

Validator::make($request->all(), [
    'title' => 'required|unique:posts|max:255',
    'body' => 'required',
])->validate();

Named Error Bags

If you have multiple forms on a single page, you may wish to name the MessageBag of errors, allowing you to retrieve the error messages for a specific form. Pass a name as the second argument to withErrors:

return redirect('register')
            ->withErrors($validator, 'login');

You may then access the named MessageBag instance from the $errors variable:

{{ $errors->login->first('email') }}

After Validation Hook

The validator also allows you to attach callbacks to be run after validation is completed. This allows you to easily perform further validation and even add more error messages to the message collection. To get started, use the after method on a validator instance:

$validator = Validator::make(...);

$validator->after(function ($validator) {
    if ($this->somethingElseIsInvalid()) {
        $validator->errors()->add('field', 'Something is wrong with this field!');
    }
});

if ($validator->fails()) {
    //
}

Working With Error Messages

After calling the errors method on a Validator instance, you will receive an IlluminateSupportMessageBag instance, which has a variety of convenient methods for working with error messages. The $errors variable that is automatically made available to all views is also an instance of the MessageBag class.

Retrieving The First Error Message For A Field

To retrieve the first error message for a given field, use the first method:

$errors = $validator->errors();

echo $errors->first('email');

Retrieving All Error Messages For A Field

If you need to retrieve an array of all the messages for a given field, use the get method:

foreach ($errors->get('email') as $message) {
    //
}

If you are validating an array form field, you may retrieve all of the messages for each of the array elements using the * character:

foreach ($errors->get('attachments.*') as $message) {
    //
}

Retrieving All Error Messages For All Fields

To retrieve an array of all messages for all fields, use the all method:

foreach ($errors->all() as $message) {
    //
}

Determining If Messages Exist For A Field

The has method may be used to determine if any error messages exist for a given field:

if ($errors->has('email')) {
    //
}

Custom Error Messages

If needed, you may use custom error messages for validation instead of the defaults. There are several ways to specify custom messages. First, you may pass the custom messages as the third argument to the Validator::make method:

$messages = [
    'required' => 'The :attribute field is required.',
];

$validator = Validator::make($input, $rules, $messages);

In this example, the :attribute placeholder will be replaced by the actual name of the field under validation. You may also utilize other placeholders in validation messages. For example:

$messages = [
    'same'    => 'The :attribute and :other must match.',
    'size'    => 'The :attribute must be exactly :size.',
    'between' => 'The :attribute value :input is not between :min - :max.',
    'in'      => 'The :attribute must be one of the following types: :values',
];

Specifying A Custom Message For A Given Attribute

Sometimes you may wish to specify a custom error message only for a specific field. You may do so using «dot» notation. Specify the attribute’s name first, followed by the rule:

$messages = [
    'email.required' => 'We need to know your e-mail address!',
];

Specifying Custom Messages In Language Files

In most cases, you will probably specify your custom messages in a language file instead of passing them directly to the Validator. To do so, add your messages to custom array in the resources/lang/xx/validation.php language file.

'custom' => [
    'email' => [
        'required' => 'We need to know your e-mail address!',
    ],
],

Specifying Custom Attributes In Language Files

If you would like the :attribute portion of your validation message to be replaced with a custom attribute name, you may specify the custom name in the attributes array of your resources/lang/xx/validation.php language file:

'attributes' => [
    'email' => 'email address',
],

Specifying Custom Values In Language Files

Sometimes you may need the :value portion of your validation message to be replaced with a custom representation of the value. For example, consider the following rule that specifies that a credit card number is required if the payment_type has a value of cc:

$request->validate([
    'credit_card_number' => 'required_if:payment_type,cc'
]);

If this validation rule fails, it will produce the following error message:

The credit card number field is required when payment type is cc.

Instead of displaying cc as the payment type value, you may specify a custom value representation in your validation language file by defining a values array:

'values' => [
    'payment_type' => [
        'cc' => 'credit card'
    ],
],

Now if the validation rule fails it will produce the following message:

The credit card number field is required when payment type is credit card.

Available Validation Rules

Below is a list of all available validation rules and their function:

<style>
.collection-method-list > p {
column-count: 3; -moz-column-count: 3; -webkit-column-count: 3;
column-gap: 2em; -moz-column-gap: 2em; -webkit-column-gap: 2em;
}

.collection-method-list a {
display: block;
}
</style>

accepted

The field under validation must be yes, on, 1, or true. This is useful for validating «Terms of Service» acceptance.

active_url

The field under validation must have a valid A or AAAA record according to the dns_get_record PHP function. The hostname of the provided URL is extracted using the parse_url PHP function before being passed to dns_get_record.

after:date

The field under validation must be a value after a given date. The dates will be passed into the strtotime PHP function:

'start_date' => 'required|date|after:tomorrow'

Instead of passing a date string to be evaluated by strtotime, you may specify another field to compare against the date:

'finish_date' => 'required|date|after:start_date'

after_or_equal:date

The field under validation must be a value after or equal to the given date. For more information, see the after rule.

alpha

The field under validation must be entirely alphabetic characters.

alpha_dash

The field under validation may have alpha-numeric characters, as well as dashes and underscores.

alpha_num

The field under validation must be entirely alpha-numeric characters.

array

The field under validation must be a PHP array.

bail

Stop running validation rules after the first validation failure.

before:date

The field under validation must be a value preceding the given date. The dates will be passed into the PHP strtotime function. In addition, like the after rule, the name of another field under validation may be supplied as the value of date.

before_or_equal:date

The field under validation must be a value preceding or equal to the given date. The dates will be passed into the PHP strtotime function. In addition, like the after rule, the name of another field under validation may be supplied as the value of date.

between:min,max

The field under validation must have a size between the given min and max. Strings, numerics, arrays, and files are evaluated in the same fashion as the size rule.

boolean

The field under validation must be able to be cast as a boolean. Accepted input are true, false, 1, 0, "1", and "0".

confirmed

The field under validation must have a matching field of foo_confirmation. For example, if the field under validation is password, a matching password_confirmation field must be present in the input.

date

The field under validation must be a valid, non-relative date according to the strtotime PHP function.

date_equals:date

The field under validation must be equal to the given date. The dates will be passed into the PHP strtotime function.

date_format:format

The field under validation must match the given format. You should use either date or date_format when validating a field, not both. This validation rule supports all formats supported by PHP’s DateTime class.

different:field

The field under validation must have a different value than field.

digits:value

The field under validation must be numeric and must have an exact length of value.

digits_between:min,max

The field under validation must be numeric and must have a length between the given min and max.

dimensions

The file under validation must be an image meeting the dimension constraints as specified by the rule’s parameters:

'avatar' => 'dimensions:min_width=100,min_height=200'

Available constraints are: min_width, max_width, min_height, max_height, width, height, ratio.

A ratio constraint should be represented as width divided by height. This can be specified either by a statement like 3/2 or a float like 1.5:

'avatar' => 'dimensions:ratio=3/2'

Since this rule requires several arguments, you may use the Rule::dimensions method to fluently construct the rule:

use IlluminateValidationRule;

Validator::make($data, [
    'avatar' => [
        'required',
        Rule::dimensions()->maxWidth(1000)->maxHeight(500)->ratio(3 / 2),
    ],
]);

distinct

When working with arrays, the field under validation must not have any duplicate values.

email

The field under validation must be formatted as an e-mail address. Under the hood, this validation rule makes use of the egulias/email-validator package for validating the email address. By default the RFCValidation validator is applied, but you can apply other validation styles as well:

'email' => 'email:rfc,dns'

The example above will apply the RFCValidation and DNSCheckValidation validations. Here’s a full list of validation styles you can apply:

— `rfc`: `RFCValidation`
— `strict`: `NoRFCWarningsValidation`
— `dns`: `DNSCheckValidation`
— `spoof`: `SpoofCheckValidation`
— `filter`: `FilterEmailValidation`

The filter validator, which uses PHP’s filter_var function under the hood, ships with Laravel and is Laravel’s pre-5.8 behavior. The dns and spoof validators require the PHP intl extension.

ends_with:foo,bar,…

The field under validation must end with one of the given values.

exclude_if:anotherfield,value

The field under validation will be excluded from the request data returned by the validate and validated methods if the anotherfield field is equal to value.

exclude_unless:anotherfield,value

The field under validation will be excluded from the request data returned by the validate and validated methods unless anotherfield‘s field is equal to value.

exists:table,column

The field under validation must exist on a given database table.

Basic Usage Of Exists Rule

'state' => 'exists:states'

If the column option is not specified, the field name will be used.

Specifying A Custom Column Name

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

Occasionally, you may need to specify a specific database connection to be used for the exists query. You can accomplish this by prepending the connection name to the table name using «dot» syntax:

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

Instead of specifying the table name directly, you may specify the Eloquent model which should be used to determine the table name:

'user_id' => 'exists:AppUser,id'

If you would like to customize the query executed by the validation rule, you may use the Rule class to fluently define the rule. In this example, we’ll also specify the validation rules as an array instead of using the | character to delimit them:

use IlluminateValidationRule;

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

file

The field under validation must be a successfully uploaded file.

filled

The field under validation must not be empty when it is present.

gt:field

The field under validation must be greater than the given field. The two fields must be of the same type. Strings, numerics, arrays, and files are evaluated using the same conventions as the size rule.

gte:field

The field under validation must be greater than or equal to the given field. The two fields must be of the same type. Strings, numerics, arrays, and files are evaluated using the same conventions as the size rule.

image

The file under validation must be an image (jpeg, png, bmp, gif, svg, or webp)

in:foo,bar,…

The field under validation must be included in the given list of values. Since this rule often requires you to implode an array, the Rule::in method may be used to fluently construct the rule:

use IlluminateValidationRule;

Validator::make($data, [
    'zones' => [
        'required',
        Rule::in(['first-zone', 'second-zone']),
    ],
]);

in_array:anotherfield.*

The field under validation must exist in anotherfield‘s values.

integer

The field under validation must be an integer.

{note} This validation rule does not verify that the input is of the «integer» variable type, only that the input is a string or numeric value that contains an integer.

ip

The field under validation must be an IP address.

ipv4

The field under validation must be an IPv4 address.

ipv6

The field under validation must be an IPv6 address.

json

The field under validation must be a valid JSON string.

lt:field

The field under validation must be less than the given field. The two fields must be of the same type. Strings, numerics, arrays, and files are evaluated using the same conventions as the size rule.

lte:field

The field under validation must be less than or equal to the given field. The two fields must be of the same type. Strings, numerics, arrays, and files are evaluated using the same conventions as the size rule.

max:value

The field under validation must be less than or equal to a maximum value. Strings, numerics, arrays, and files are evaluated in the same fashion as the size rule.

mimetypes:text/plain,…

The file under validation must match one of the given MIME types:

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

To determine the MIME type of the uploaded file, the file’s contents will be read and the framework will attempt to guess the MIME type, which may be different from the client provided MIME type.

mimes:foo,bar,…

The file under validation must have a MIME type corresponding to one of the listed extensions.

Basic Usage Of MIME Rule

'photo' => 'mimes:jpeg,bmp,png'

Even though you only need to specify the extensions, this rule actually validates against the MIME type of the file by reading the file’s contents and guessing its MIME type.

A full listing of MIME types and their corresponding extensions may be found at the following location: https://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types

min:value

The field under validation must have a minimum value. Strings, numerics, arrays, and files are evaluated in the same fashion as the size rule.

not_in:foo,bar,…

The field under validation must not be included in the given list of values. The Rule::notIn method may be used to fluently construct the rule:

use IlluminateValidationRule;

Validator::make($data, [
    'toppings' => [
        'required',
        Rule::notIn(['sprinkles', 'cherries']),
    ],
]);

not_regex:pattern

The field under validation must not match the given regular expression.

Internally, this rule uses the PHP preg_match function. The pattern specified should obey the same formatting required by preg_match and thus also include valid delimiters. For example: 'email' => 'not_regex:/^.+$/i'.

Note: When using the regex / not_regex patterns, it may be necessary to specify rules in an array instead of using pipe delimiters, especially if the regular expression contains a pipe character.

nullable

The field under validation may be null. This is particularly useful when validating primitive such as strings and integers that can contain null values.

numeric

The field under validation must be numeric.

password

The field under validation must match the authenticated user’s password. You may specify an authentication guard using the rule’s first parameter:

'password' => 'password:api'

present

The field under validation must be present in the input data but can be empty.

regex:pattern

The field under validation must match the given regular expression.

Internally, this rule uses the PHP preg_match function. The pattern specified should obey the same formatting required by preg_match and thus also include valid delimiters. For example: 'email' => 'regex:/^.+@.+$/i'.

Note: When using the regex / not_regex patterns, it may be necessary to specify rules in an array instead of using pipe delimiters, especially if the regular expression contains a pipe character.

required

The field under validation must be present in the input data and not empty. A field is considered «empty» if one of the following conditions are true:

  • The value is null.
  • The value is an empty string.
  • The value is an empty array or empty Countable object.
  • The value is an uploaded file with no path.

required_if:anotherfield,value,…

The field under validation must be present and not empty if the anotherfield field is equal to any value.

If you would like to construct a more complex condition for the required_if rule, you may use the Rule::requiredIf method. This methods accepts a boolean or a Closure. When passed a Closure, the Closure should return true or false to indicate if the field under validation is required:

use IlluminateValidationRule;

Validator::make($request->all(), [
    'role_id' => Rule::requiredIf($request->user()->is_admin),
]);

Validator::make($request->all(), [
    'role_id' => Rule::requiredIf(function () use ($request) {
        return $request->user()->is_admin;
    }),
]);

required_unless:anotherfield,value,…

The field under validation must be present and not empty unless the anotherfield field is equal to any value.

required_with:foo,bar,…

The field under validation must be present and not empty only if any of the other specified fields are present.

required_with_all:foo,bar,…

The field under validation must be present and not empty only if all of the other specified fields are present.

required_without:foo,bar,…

The field under validation must be present and not empty only when any of the other specified fields are not present.

required_without_all:foo,bar,…

The field under validation must be present and not empty only when all of the other specified fields are not present.

same:field

The given field must match the field under validation.

size:value

The field under validation must have a size matching the given value. For string data, value corresponds to the number of characters. For numeric data, value corresponds to a given integer value. For an array, size corresponds to the count of the array. For files, size corresponds to the file size in kilobytes.

starts_with:foo,bar,…

The field under validation must start with one of the given values.

string

The field under validation must be a string. If you would like to allow the field to also be null, you should assign the nullable rule to the field.

timezone

The field under validation must be a valid timezone identifier according to the timezone_identifiers_list PHP function.

unique:table,column,except,idColumn

The field under validation must not exist within the given database table.

Specifying A Custom Table / Column Name:

Instead of specifying the table name directly, you may specify the Eloquent model which should be used to determine the table name:

'email' => 'unique:AppUser,email_address'

The column option may be used to specify the field’s corresponding database column. If the column option is not specified, the field name will be used.

'email' => 'unique:users,email_address'

Custom Database Connection

Occasionally, you may need to set a custom connection for database queries made by the Validator. As seen above, setting unique:users as a validation rule will use the default database connection to query the database. To override this, specify the connection and the table name using «dot» syntax:

'email' => 'unique:connection.users,email_address'

Forcing A Unique Rule To Ignore A Given ID:

Sometimes, you may wish to ignore a given ID during the unique check. For example, consider an «update profile» screen that includes the user’s name, e-mail address, and location. You will probably want to verify that the e-mail address is unique. However, if the user only changes the name field and not the e-mail field, you do not want a validation error to be thrown because the user is already the owner of the e-mail address.

To instruct the validator to ignore the user’s ID, we’ll use the Rule class to fluently define the rule. In this example, we’ll also specify the validation rules as an array instead of using the | character to delimit the rules:

use IlluminateValidationRule;

Validator::make($data, [
    'email' => [
        'required',
        Rule::unique('users')->ignore($user->id),
    ],
]);

{note} You should never pass any user controlled request input into the ignore method. Instead, you should only pass a system generated unique ID such as an auto-incrementing ID or UUID from an Eloquent model instance. Otherwise, your application will be vulnerable to an SQL injection attack.

Instead of passing the model key’s value to the ignore method, you may pass the entire model instance. Laravel will automatically extract the key from the model:

Rule::unique('users')->ignore($user)

If your table uses a primary key column name other than id, you may specify the name of the column when calling the ignore method:

Rule::unique('users')->ignore($user->id, 'user_id')

By default, the unique rule will check the uniqueness of the column matching the name of the attribute being validated. However, you may pass a different column name as the second argument to the unique method:

Rule::unique('users', 'email_address')->ignore($user->id),

Adding Additional Where Clauses:

You may also specify additional query constraints by customizing the query using the where method. For example, let’s add a constraint that verifies the account_id is 1:

'email' => Rule::unique('users')->where(function ($query) {
    return $query->where('account_id', 1);
})

url

The field under validation must be a valid URL.

uuid

The field under validation must be a valid RFC 4122 (version 1, 3, 4, or 5) universally unique identifier (UUID).

Conditionally Adding Rules

Validating When Present

In some situations, you may wish to run validation checks against a field only if that field is present in the input array. To quickly accomplish this, add the sometimes rule to your rule list:

$v = Validator::make($data, [
    'email' => 'sometimes|required|email',
]);

In the example above, the email field will only be validated if it is present in the $data array.

{tip} If you are attempting to validate a field that should always be present but may be empty, check out this note on optional fields

Complex Conditional Validation

Sometimes you may wish to add validation rules based on more complex conditional logic. For example, you may wish to require a given field only if another field has a greater value than 100. Or, you may need two fields to have a given value only when another field is present. Adding these validation rules doesn’t have to be a pain. First, create a Validator instance with your static rules that never change:

$v = Validator::make($data, [
    'email' => 'required|email',
    'games' => 'required|numeric',
]);

Let’s assume our web application is for game collectors. If a game collector registers with our application and they own more than 100 games, we want them to explain why they own so many games. For example, perhaps they run a game resale shop, or maybe they just enjoy collecting. To conditionally add this requirement, we can use the sometimes method on the Validator instance.

$v->sometimes('reason', 'required|max:500', function ($input) {
    return $input->games >= 100;
});

The first argument passed to the sometimes method is the name of the field we are conditionally validating. The second argument is the rules we want to add. If the Closure passed as the third argument returns true, the rules will be added. This method makes it a breeze to build complex conditional validations. You may even add conditional validations for several fields at once:

$v->sometimes(['reason', 'cost'], 'required', function ($input) {
    return $input->games >= 100;
});

{tip} The $input parameter passed to your Closure will be an instance of IlluminateSupportFluent and may be used to access your input and files.

Validating Arrays

Validating array based form input fields doesn’t have to be a pain. You may use «dot notation» to validate attributes within an array. For example, if the incoming HTTP request contains a photos[profile] field, you may validate it like so:

$validator = Validator::make($request->all(), [
    'photos.profile' => 'required|image',
]);

You may also validate each element of an array. For example, to validate that each e-mail in a given array input field is unique, you may do the following:

$validator = Validator::make($request->all(), [
    'person.*.email' => 'email|unique:users',
    'person.*.first_name' => 'required_with:person.*.last_name',
]);

Likewise, you may use the * character when specifying your validation messages in your language files, making it a breeze to use a single validation message for array based fields:

'custom' => [
    'person.*.email' => [
        'unique' => 'Each person must have a unique e-mail address',
    ]
],

Custom Validation Rules

Using Rule Objects

Laravel provides a variety of helpful validation rules; however, you may wish to specify some of your own. One method of registering custom validation rules is using rule objects. To generate a new rule object, you may use the make:rule Artisan command. Let’s use this command to generate a rule that verifies a string is uppercase. Laravel will place the new rule in the app/Rules directory:

php artisan make:rule Uppercase

Once the rule has been created, we are ready to define its behavior. A rule object contains two methods: passes and message. The passes method receives the attribute value and name, and should return true or false depending on whether the attribute value is valid or not. The message method should return the validation error message that should be used when validation fails:

<?php

namespace AppRules;

use IlluminateContractsValidationRule;

class Uppercase implements Rule
{
    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        return strtoupper($value) === $value;
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'The :attribute must be uppercase.';
    }
}

You may call the trans helper from your message method if you would like to return an error message from your translation files:

/**
 * Get the validation error message.
 *
 * @return string
 */
public function message()
{
    return trans('validation.uppercase');
}

Once the rule has been defined, you may attach it to a validator by passing an instance of the rule object with your other validation rules:

use AppRulesUppercase;

$request->validate([
    'name' => ['required', 'string', new Uppercase],
]);

Using Closures

If you only need the functionality of a custom rule once throughout your application, you may use a Closure instead of a rule object. The Closure receives the attribute’s name, the attribute’s value, and a $fail callback that should be called if validation fails:

$validator = Validator::make($request->all(), [
    'title' => [
        'required',
        'max:255',
        function ($attribute, $value, $fail) {
            if ($value === 'foo') {
                $fail($attribute.' is invalid.');
            }
        },
    ],
]);

Using Extensions

Another method of registering custom validation rules is using the extend method on the Validator facade. Let’s use this method within a service provider to register a custom validation rule:

<?php

namespace AppProviders;

use IlluminateSupportServiceProvider;
use IlluminateSupportFacadesValidator;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Validator::extend('foo', function ($attribute, $value, $parameters, $validator) {
            return $value == 'foo';
        });
    }
}

The custom validator Closure receives four arguments: the name of the $attribute being validated, the $value of the attribute, an array of $parameters passed to the rule, and the Validator instance.

You may also pass a class and method to the extend method instead of a Closure:

Validator::extend('foo', 'FooValidator@validate');

Defining The Error Message

You will also need to define an error message for your custom rule. You can do so either using an inline custom message array or by adding an entry in the validation language file. This message should be placed in the first level of the array, not within the custom array, which is only for attribute-specific error messages:

"foo" => "Your input was invalid!",

"accepted" => "The :attribute must be accepted.",

// The rest of the validation error messages...

When creating a custom validation rule, you may sometimes need to define custom placeholder replacements for error messages. You may do so by creating a custom Validator as described above then making a call to the replacer method on the Validator facade. You may do this within the boot method of a service provider:

/**
 * Bootstrap any application services.
 *
 * @return void
 */
public function boot()
{
    Validator::extend(...);

    Validator::replacer('foo', function ($message, $attribute, $rule, $parameters) {
        return str_replace(...);
    });
}

Implicit Extensions

By default, when an attribute being validated is not present or contains an empty string, normal validation rules, including custom extensions, are not run. For example, the unique rule will not be run against an empty string:

$rules = ['name' => 'unique:users,name'];

$input = ['name' => ''];

Validator::make($input, $rules)->passes(); // true

For a rule to run even when an attribute is empty, the rule must imply that the attribute is required. To create such an «implicit» extension, use the Validator::extendImplicit() method:

Validator::extendImplicit('foo', function ($attribute, $value, $parameters, $validator) {
    return $value == 'foo';
});

{note} An «implicit» extension only implies that the attribute is required. Whether it actually invalidates a missing or empty attribute is up to you.

Implicit Rule Objects

If you would like a rule object to run when an attribute is empty, you should implement the IlluminateContractsValidationImplicitRule interface. This interface serves as a «marker interface» for the validator; therefore, it does not contain any methods you need to implement.

Validation

  • Introduction
  • Validation Quickstart
    • Defining The Routes
    • Creating The Controller
    • Writing The Validation Logic
    • Displaying The Validation Errors
    • A Note On Optional Fields
  • Form Request Validation
    • Creating Form Requests
    • Authorizing Form Requests
    • Customizing The Error Messages
    • Customizing The Validation Attributes
    • Prepare Input For Validation
  • Manually Creating Validators
    • Automatic Redirection
    • Named Error Bags
    • After Validation Hook
  • Working With Error Messages
    • Custom Error Messages
  • Available Validation Rules
  • Conditionally Adding Rules
  • Validating Arrays
  • Custom Validation Rules
    • Using Rule Objects
    • Using Closures
    • Using Extensions
    • Implicit Extensions

Introduction

Laravel provides several different approaches to validate your application’s incoming data. By default, Laravel’s base controller class uses a ValidatesRequests trait which provides a convenient method to validate incoming HTTP request with a variety of powerful validation rules.

Validation Quickstart

To learn about Laravel’s powerful validation features, let’s look at a complete example of validating a form and displaying the error messages back to the user.

Defining The Routes

First, let’s assume we have the following routes defined in our routes/web.php file:

Route::get('post/create', 'PostController@create');

Route::post('post', 'PostController@store');

The GET route will display a form for the user to create a new blog post, while the POST route will store the new blog post in the database.

Creating The Controller

Next, let’s take a look at a simple controller that handles these routes. We’ll leave the store method empty for now:

<?php

namespace AppHttpControllers;

use AppHttpControllersController;
use IlluminateHttpRequest;

class PostController extends Controller
{
    /**
     * Show the form to create a new blog post.
     *
     * @return Response
     */
    public function create()
    {
        return view('post.create');
    }

    /**
     * Store a new blog post.
     *
     * @param  Request  $request
     * @return Response
     */
    public function store(Request $request)
    {
        // Validate and store the blog post...
    }
}

Writing The Validation Logic

Now we are ready to fill in our store method with the logic to validate the new blog post. To do this, we will use the validate method provided by the IlluminateHttpRequest object. If the validation rules pass, your code will keep executing normally; however, if validation fails, an exception will be thrown and the proper error response will automatically be sent back to the user. In the case of a traditional HTTP request, a redirect response will be generated, while a JSON response will be sent for AJAX requests.

To get a better understanding of the validate method, let’s jump back into the store method:

/**
 * Store a new blog post.
 *
 * @param  Request  $request
 * @return Response
 */
public function store(Request $request)
{
    $validatedData = $request->validate([
        'title' => 'required|unique:posts|max:255',
        'body' => 'required',
    ]);

    // The blog post is valid...
}

As you can see, we pass the desired validation rules into the validate method. Again, if the validation fails, the proper response will automatically be generated. If the validation passes, our controller will continue executing normally.

Alternatively, validation rules may be specified as arrays of rules instead of a single | delimited string:

$validatedData = $request->validate([
    'title' => ['required', 'unique:posts', 'max:255'],
    'body' => ['required'],
]);

If you would like to specify the error bag in which the error messages should be placed, you may use the validateWithBag method:

$request->validateWithBag('blog', [
    'title' => ['required', 'unique:posts', 'max:255'],
    'body' => ['required'],
]);

Stopping On First Validation Failure

Sometimes you may wish to stop running validation rules on an attribute after the first validation failure. To do so, assign the bail rule to the attribute:

$request->validate([
    'title' => 'bail|required|unique:posts|max:255',
    'body' => 'required',
]);

In this example, if the unique rule on the title attribute fails, the max rule will not be checked. Rules will be validated in the order they are assigned.

A Note On Nested Attributes

If your HTTP request contains «nested» parameters, you may specify them in your validation rules using «dot» syntax:

$request->validate([
    'title' => 'required|unique:posts|max:255',
    'author.name' => 'required',
    'author.description' => 'required',
]);

Displaying The Validation Errors

So, what if the incoming request parameters do not pass the given validation rules? As mentioned previously, Laravel will automatically redirect the user back to their previous location. In addition, all of the validation errors will automatically be flashed to the session.

Again, notice that we did not have to explicitly bind the error messages to the view in our GET route. This is because Laravel will check for errors in the session data, and automatically bind them to the view if they are available. The $errors variable will be an instance of IlluminateSupportMessageBag. For more information on working with this object, check out its documentation.

{tip} The $errors variable is bound to the view by the IlluminateViewMiddlewareShareErrorsFromSession middleware, which is provided by the web middleware group. When this middleware is applied an $errors variable will always be available in your views, allowing you to conveniently assume the $errors variable is always defined and can be safely used.

So, in our example, the user will be redirected to our controller’s create method when validation fails, allowing us to display the error messages in the view:

<!-- /resources/views/post/create.blade.php -->

<h1>Create Post</h1>

@if ($errors->any())
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

<!-- Create Post Form -->

The @error Directive

You may also use the @error Blade directive to quickly check if validation error messages exist for a given attribute. Within an @error directive, you may echo the $message variable to display the error message:

<!-- /resources/views/post/create.blade.php -->

<label for="title">Post Title</label>

<input id="title" type="text" class="@error('title') is-invalid @enderror">

@error('title')
    <div class="alert alert-danger">{{ $message }}</div>
@enderror

A Note On Optional Fields

By default, Laravel includes the TrimStrings and ConvertEmptyStringsToNull middleware in your application’s global middleware stack. These middleware are listed in the stack by the AppHttpKernel class. Because of this, you will often need to mark your «optional» request fields as nullable if you do not want the validator to consider null values as invalid. For example:

$request->validate([
    'title' => 'required|unique:posts|max:255',
    'body' => 'required',
    'publish_at' => 'nullable|date',
]);

In this example, we are specifying that the publish_at field may be either null or a valid date representation. If the nullable modifier is not added to the rule definition, the validator would consider null an invalid date.

AJAX Requests & Validation

In this example, we used a traditional form to send data to the application. However, many applications use AJAX requests. When using the validate method during an AJAX request, Laravel will not generate a redirect response. Instead, Laravel generates a JSON response containing all of the validation errors. This JSON response will be sent with a 422 HTTP status code.

Form Request Validation

Creating Form Requests

For more complex validation scenarios, you may wish to create a «form request». Form requests are custom request classes that contain validation logic. To create a form request class, use the make:request Artisan CLI command:

php artisan make:request StoreBlogPost

The generated class will be placed in the app/Http/Requests directory. If this directory does not exist, it will be created when you run the make:request command. Let’s add a few validation rules to the rules method:

/**
 * Get the validation rules that apply to the request.
 *
 * @return array
 */
public function rules()
{
    return [
        'title' => 'required|unique:posts|max:255',
        'body' => 'required',
    ];
}

{tip} You may type-hint any dependencies you need within the rules method’s signature. They will automatically be resolved via the Laravel service container.

So, how are the validation rules evaluated? All you need to do is type-hint the request on your controller method. The incoming form request is validated before the controller method is called, meaning you do not need to clutter your controller with any validation logic:

/**
 * Store the incoming blog post.
 *
 * @param  StoreBlogPost  $request
 * @return Response
 */
public function store(StoreBlogPost $request)
{
    // The incoming request is valid...

    // Retrieve the validated input data...
    $validated = $request->validated();
}

If validation fails, a redirect response will be generated to send the user back to their previous location. The errors will also be flashed to the session so they are available for display. If the request was an AJAX request, a HTTP response with a 422 status code will be returned to the user including a JSON representation of the validation errors.

Adding After Hooks To Form Requests

If you would like to add an «after» hook to a form request, you may use the withValidator method. This method receives the fully constructed validator, allowing you to call any of its methods before the validation rules are actually evaluated:

/**
 * Configure the validator instance.
 *
 * @param  IlluminateValidationValidator  $validator
 * @return void
 */
public function withValidator($validator)
{
    $validator->after(function ($validator) {
        if ($this->somethingElseIsInvalid()) {
            $validator->errors()->add('field', 'Something is wrong with this field!');
        }
    });
}

Authorizing Form Requests

The form request class also contains an authorize method. Within this method, you may check if the authenticated user actually has the authority to update a given resource. For example, you may determine if a user actually owns a blog comment they are attempting to update:

/**
 * Determine if the user is authorized to make this request.
 *
 * @return bool
 */
public function authorize()
{
    $comment = Comment::find($this->route('comment'));

    return $comment && $this->user()->can('update', $comment);
}

Since all form requests extend the base Laravel request class, we may use the user method to access the currently authenticated user. Also note the call to the route method in the example above. This method grants you access to the URI parameters defined on the route being called, such as the {comment} parameter in the example below:

Route::post('comment/{comment}');

If the authorize method returns false, a HTTP response with a 403 status code will automatically be returned and your controller method will not execute.

If you plan to have authorization logic in another part of your application, return true from the authorize method:

/**
 * Determine if the user is authorized to make this request.
 *
 * @return bool
 */
public function authorize()
{
    return true;
}

{tip} You may type-hint any dependencies you need within the authorize method’s signature. They will automatically be resolved via the Laravel service container.

Customizing The Error Messages

You may customize the error messages used by the form request by overriding the messages method. This method should return an array of attribute / rule pairs and their corresponding error messages:

/**
 * Get the error messages for the defined validation rules.
 *
 * @return array
 */
public function messages()
{
    return [
        'title.required' => 'A title is required',
        'body.required'  => 'A message is required',
    ];
}

Customizing The Validation Attributes

If you would like the :attribute portion of your validation message to be replaced with a custom attribute name, you may specify the custom names by overriding the attributes method. This method should return an array of attribute / name pairs:

/**
 * Get custom attributes for validator errors.
 *
 * @return array
 */
public function attributes()
{
    return [
        'email' => 'email address',
    ];
}

Prepare Input For Validation

If you need to sanitize any data from the request before you apply your validation rules, you can use the prepareForValidation method:

use IlluminateSupportStr;

/**
 * Prepare the data for validation.
 *
 * @return void
 */
protected function prepareForValidation()
{
    $this->merge([
        'slug' => Str::slug($this->slug),
    ]);
}

Manually Creating Validators

If you do not want to use the validate method on the request, you may create a validator instance manually using the Validator facade. The make method on the facade generates a new validator instance:

<?php

namespace AppHttpControllers;

use AppHttpControllersController;
use IlluminateHttpRequest;
use IlluminateSupportFacadesValidator;

class PostController extends Controller
{
    /**
     * Store a new blog post.
     *
     * @param  Request  $request
     * @return Response
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'title' => 'required|unique:posts|max:255',
            'body' => 'required',
        ]);

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

        // Store the blog post...
    }
}

The first argument passed to the make method is the data under validation. The second argument is the validation rules that should be applied to the data.

After checking if the request validation failed, you may use the withErrors method to flash the error messages to the session. When using this method, the $errors variable will automatically be shared with your views after redirection, allowing you to easily display them back to the user. The withErrors method accepts a validator, a MessageBag, or a PHP array.

Automatic Redirection

If you would like to create a validator instance manually but still take advantage of the automatic redirection offered by the request’s validate method, you may call the validate method on an existing validator instance. If validation fails, the user will automatically be redirected or, in the case of an AJAX request, a JSON response will be returned:

Validator::make($request->all(), [
    'title' => 'required|unique:posts|max:255',
    'body' => 'required',
])->validate();

Named Error Bags

If you have multiple forms on a single page, you may wish to name the MessageBag of errors, allowing you to retrieve the error messages for a specific form. Pass a name as the second argument to withErrors:

return redirect('register')
            ->withErrors($validator, 'login');

You may then access the named MessageBag instance from the $errors variable:

{{ $errors->login->first('email') }}

After Validation Hook

The validator also allows you to attach callbacks to be run after validation is completed. This allows you to easily perform further validation and even add more error messages to the message collection. To get started, use the after method on a validator instance:

$validator = Validator::make(...);

$validator->after(function ($validator) {
    if ($this->somethingElseIsInvalid()) {
        $validator->errors()->add('field', 'Something is wrong with this field!');
    }
});

if ($validator->fails()) {
    //
}

Working With Error Messages

After calling the errors method on a Validator instance, you will receive an IlluminateSupportMessageBag instance, which has a variety of convenient methods for working with error messages. The $errors variable that is automatically made available to all views is also an instance of the MessageBag class.

Retrieving The First Error Message For A Field

To retrieve the first error message for a given field, use the first method:

$errors = $validator->errors();

echo $errors->first('email');

Retrieving All Error Messages For A Field

If you need to retrieve an array of all the messages for a given field, use the get method:

foreach ($errors->get('email') as $message) {
    //
}

If you are validating an array form field, you may retrieve all of the messages for each of the array elements using the * character:

foreach ($errors->get('attachments.*') as $message) {
    //
}

Retrieving All Error Messages For All Fields

To retrieve an array of all messages for all fields, use the all method:

foreach ($errors->all() as $message) {
    //
}

Determining If Messages Exist For A Field

The has method may be used to determine if any error messages exist for a given field:

if ($errors->has('email')) {
    //
}

Custom Error Messages

If needed, you may use custom error messages for validation instead of the defaults. There are several ways to specify custom messages. First, you may pass the custom messages as the third argument to the Validator::make method:

$messages = [
    'required' => 'The :attribute field is required.',
];

$validator = Validator::make($input, $rules, $messages);

In this example, the :attribute placeholder will be replaced by the actual name of the field under validation. You may also utilize other placeholders in validation messages. For example:

$messages = [
    'same'    => 'The :attribute and :other must match.',
    'size'    => 'The :attribute must be exactly :size.',
    'between' => 'The :attribute value :input is not between :min - :max.',
    'in'      => 'The :attribute must be one of the following types: :values',
];

Specifying A Custom Message For A Given Attribute

Sometimes you may wish to specify a custom error message only for a specific field. You may do so using «dot» notation. Specify the attribute’s name first, followed by the rule:

$messages = [
    'email.required' => 'We need to know your e-mail address!',
];

Specifying Custom Messages In Language Files

In most cases, you will probably specify your custom messages in a language file instead of passing them directly to the Validator. To do so, add your messages to custom array in the resources/lang/xx/validation.php language file.

'custom' => [
    'email' => [
        'required' => 'We need to know your e-mail address!',
    ],
],

Specifying Custom Attributes In Language Files

If you would like the :attribute portion of your validation message to be replaced with a custom attribute name, you may specify the custom name in the attributes array of your resources/lang/xx/validation.php language file:

'attributes' => [
    'email' => 'email address',
],

Specifying Custom Values In Language Files

Sometimes you may need the :value portion of your validation message to be replaced with a custom representation of the value. For example, consider the following rule that specifies that a credit card number is required if the payment_type has a value of cc:

$request->validate([
    'credit_card_number' => 'required_if:payment_type,cc'
]);

If this validation rule fails, it will produce the following error message:

The credit card number field is required when payment type is cc.

Instead of displaying cc as the payment type value, you may specify a custom value representation in your validation language file by defining a values array:

'values' => [
    'payment_type' => [
        'cc' => 'credit card'
    ],
],

Now if the validation rule fails it will produce the following message:

The credit card number field is required when payment type is credit card.

Available Validation Rules

Below is a list of all available validation rules and their function:

<style>
.collection-method-list > p {
column-count: 3; -moz-column-count: 3; -webkit-column-count: 3;
column-gap: 2em; -moz-column-gap: 2em; -webkit-column-gap: 2em;
}

.collection-method-list a {
display: block;
}
</style>

accepted

The field under validation must be yes, on, 1, or true. This is useful for validating «Terms of Service» acceptance.

active_url

The field under validation must have a valid A or AAAA record according to the dns_get_record PHP function. The hostname of the provided URL is extracted using the parse_url PHP function before being passed to dns_get_record.

after:date

The field under validation must be a value after a given date. The dates will be passed into the strtotime PHP function:

'start_date' => 'required|date|after:tomorrow'

Instead of passing a date string to be evaluated by strtotime, you may specify another field to compare against the date:

'finish_date' => 'required|date|after:start_date'

after_or_equal:date

The field under validation must be a value after or equal to the given date. For more information, see the after rule.

alpha

The field under validation must be entirely alphabetic characters.

alpha_dash

The field under validation may have alpha-numeric characters, as well as dashes and underscores.

alpha_num

The field under validation must be entirely alpha-numeric characters.

array

The field under validation must be a PHP array.

bail

Stop running validation rules after the first validation failure.

before:date

The field under validation must be a value preceding the given date. The dates will be passed into the PHP strtotime function. In addition, like the after rule, the name of another field under validation may be supplied as the value of date.

before_or_equal:date

The field under validation must be a value preceding or equal to the given date. The dates will be passed into the PHP strtotime function. In addition, like the after rule, the name of another field under validation may be supplied as the value of date.

between:min,max

The field under validation must have a size between the given min and max. Strings, numerics, arrays, and files are evaluated in the same fashion as the size rule.

boolean

The field under validation must be able to be cast as a boolean. Accepted input are true, false, 1, 0, "1", and "0".

confirmed

The field under validation must have a matching field of foo_confirmation. For example, if the field under validation is password, a matching password_confirmation field must be present in the input.

date

The field under validation must be a valid, non-relative date according to the strtotime PHP function.

date_equals:date

The field under validation must be equal to the given date. The dates will be passed into the PHP strtotime function.

date_format:format

The field under validation must match the given format. You should use either date or date_format when validating a field, not both. This validation rule supports all formats supported by PHP’s DateTime class.

different:field

The field under validation must have a different value than field.

digits:value

The field under validation must be numeric and must have an exact length of value.

digits_between:min,max

The field under validation must be numeric and must have a length between the given min and max.

dimensions

The file under validation must be an image meeting the dimension constraints as specified by the rule’s parameters:

'avatar' => 'dimensions:min_width=100,min_height=200'

Available constraints are: min_width, max_width, min_height, max_height, width, height, ratio.

A ratio constraint should be represented as width divided by height. This can be specified either by a statement like 3/2 or a float like 1.5:

'avatar' => 'dimensions:ratio=3/2'

Since this rule requires several arguments, you may use the Rule::dimensions method to fluently construct the rule:

use IlluminateValidationRule;

Validator::make($data, [
    'avatar' => [
        'required',
        Rule::dimensions()->maxWidth(1000)->maxHeight(500)->ratio(3 / 2),
    ],
]);

distinct

When working with arrays, the field under validation must not have any duplicate values.

email

The field under validation must be formatted as an e-mail address. Under the hood, this validation rule makes use of the egulias/email-validator package for validating the email address. By default the RFCValidation validator is applied, but you can apply other validation styles as well:

'email' => 'email:rfc,dns'

The example above will apply the RFCValidation and DNSCheckValidation validations. Here’s a full list of validation styles you can apply:

— `rfc`: `RFCValidation`
— `strict`: `NoRFCWarningsValidation`
— `dns`: `DNSCheckValidation`
— `spoof`: `SpoofCheckValidation`
— `filter`: `FilterEmailValidation`

The filter validator, which uses PHP’s filter_var function under the hood, ships with Laravel and is Laravel’s pre-5.8 behavior. The dns and spoof validators require the PHP intl extension.

ends_with:foo,bar,…

The field under validation must end with one of the given values.

exclude_if:anotherfield,value

The field under validation will be excluded from the request data returned by the validate and validated methods if the anotherfield field is equal to value.

exclude_unless:anotherfield,value

The field under validation will be excluded from the request data returned by the validate and validated methods unless anotherfield‘s field is equal to value.

exists:table,column

The field under validation must exist on a given database table.

Basic Usage Of Exists Rule

'state' => 'exists:states'

If the column option is not specified, the field name will be used.

Specifying A Custom Column Name

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

Occasionally, you may need to specify a specific database connection to be used for the exists query. You can accomplish this by prepending the connection name to the table name using «dot» syntax:

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

Instead of specifying the table name directly, you may specify the Eloquent model which should be used to determine the table name:

'user_id' => 'exists:AppUser,id'

If you would like to customize the query executed by the validation rule, you may use the Rule class to fluently define the rule. In this example, we’ll also specify the validation rules as an array instead of using the | character to delimit them:

use IlluminateValidationRule;

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

file

The field under validation must be a successfully uploaded file.

filled

The field under validation must not be empty when it is present.

gt:field

The field under validation must be greater than the given field. The two fields must be of the same type. Strings, numerics, arrays, and files are evaluated using the same conventions as the size rule.

gte:field

The field under validation must be greater than or equal to the given field. The two fields must be of the same type. Strings, numerics, arrays, and files are evaluated using the same conventions as the size rule.

image

The file under validation must be an image (jpeg, png, bmp, gif, svg, or webp)

in:foo,bar,…

The field under validation must be included in the given list of values. Since this rule often requires you to implode an array, the Rule::in method may be used to fluently construct the rule:

use IlluminateValidationRule;

Validator::make($data, [
    'zones' => [
        'required',
        Rule::in(['first-zone', 'second-zone']),
    ],
]);

in_array:anotherfield.*

The field under validation must exist in anotherfield‘s values.

integer

The field under validation must be an integer.

{note} This validation rule does not verify that the input is of the «integer» variable type, only that the input is a string or numeric value that contains an integer.

ip

The field under validation must be an IP address.

ipv4

The field under validation must be an IPv4 address.

ipv6

The field under validation must be an IPv6 address.

json

The field under validation must be a valid JSON string.

lt:field

The field under validation must be less than the given field. The two fields must be of the same type. Strings, numerics, arrays, and files are evaluated using the same conventions as the size rule.

lte:field

The field under validation must be less than or equal to the given field. The two fields must be of the same type. Strings, numerics, arrays, and files are evaluated using the same conventions as the size rule.

max:value

The field under validation must be less than or equal to a maximum value. Strings, numerics, arrays, and files are evaluated in the same fashion as the size rule.

mimetypes:text/plain,…

The file under validation must match one of the given MIME types:

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

To determine the MIME type of the uploaded file, the file’s contents will be read and the framework will attempt to guess the MIME type, which may be different from the client provided MIME type.

mimes:foo,bar,…

The file under validation must have a MIME type corresponding to one of the listed extensions.

Basic Usage Of MIME Rule

'photo' => 'mimes:jpeg,bmp,png'

Even though you only need to specify the extensions, this rule actually validates against the MIME type of the file by reading the file’s contents and guessing its MIME type.

A full listing of MIME types and their corresponding extensions may be found at the following location: https://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types

min:value

The field under validation must have a minimum value. Strings, numerics, arrays, and files are evaluated in the same fashion as the size rule.

not_in:foo,bar,…

The field under validation must not be included in the given list of values. The Rule::notIn method may be used to fluently construct the rule:

use IlluminateValidationRule;

Validator::make($data, [
    'toppings' => [
        'required',
        Rule::notIn(['sprinkles', 'cherries']),
    ],
]);

not_regex:pattern

The field under validation must not match the given regular expression.

Internally, this rule uses the PHP preg_match function. The pattern specified should obey the same formatting required by preg_match and thus also include valid delimiters. For example: 'email' => 'not_regex:/^.+$/i'.

Note: When using the regex / not_regex patterns, it may be necessary to specify rules in an array instead of using pipe delimiters, especially if the regular expression contains a pipe character.

nullable

The field under validation may be null. This is particularly useful when validating primitive such as strings and integers that can contain null values.

numeric

The field under validation must be numeric.

password

The field under validation must match the authenticated user’s password. You may specify an authentication guard using the rule’s first parameter:

'password' => 'password:api'

present

The field under validation must be present in the input data but can be empty.

regex:pattern

The field under validation must match the given regular expression.

Internally, this rule uses the PHP preg_match function. The pattern specified should obey the same formatting required by preg_match and thus also include valid delimiters. For example: 'email' => 'regex:/^.+@.+$/i'.

Note: When using the regex / not_regex patterns, it may be necessary to specify rules in an array instead of using pipe delimiters, especially if the regular expression contains a pipe character.

required

The field under validation must be present in the input data and not empty. A field is considered «empty» if one of the following conditions are true:

  • The value is null.
  • The value is an empty string.
  • The value is an empty array or empty Countable object.
  • The value is an uploaded file with no path.

required_if:anotherfield,value,…

The field under validation must be present and not empty if the anotherfield field is equal to any value.

If you would like to construct a more complex condition for the required_if rule, you may use the Rule::requiredIf method. This methods accepts a boolean or a Closure. When passed a Closure, the Closure should return true or false to indicate if the field under validation is required:

use IlluminateValidationRule;

Validator::make($request->all(), [
    'role_id' => Rule::requiredIf($request->user()->is_admin),
]);

Validator::make($request->all(), [
    'role_id' => Rule::requiredIf(function () use ($request) {
        return $request->user()->is_admin;
    }),
]);

required_unless:anotherfield,value,…

The field under validation must be present and not empty unless the anotherfield field is equal to any value.

required_with:foo,bar,…

The field under validation must be present and not empty only if any of the other specified fields are present.

required_with_all:foo,bar,…

The field under validation must be present and not empty only if all of the other specified fields are present.

required_without:foo,bar,…

The field under validation must be present and not empty only when any of the other specified fields are not present.

required_without_all:foo,bar,…

The field under validation must be present and not empty only when all of the other specified fields are not present.

same:field

The given field must match the field under validation.

size:value

The field under validation must have a size matching the given value. For string data, value corresponds to the number of characters. For numeric data, value corresponds to a given integer value. For an array, size corresponds to the count of the array. For files, size corresponds to the file size in kilobytes.

starts_with:foo,bar,…

The field under validation must start with one of the given values.

string

The field under validation must be a string. If you would like to allow the field to also be null, you should assign the nullable rule to the field.

timezone

The field under validation must be a valid timezone identifier according to the timezone_identifiers_list PHP function.

unique:table,column,except,idColumn

The field under validation must not exist within the given database table.

Specifying A Custom Table / Column Name:

Instead of specifying the table name directly, you may specify the Eloquent model which should be used to determine the table name:

'email' => 'unique:AppUser,email_address'

The column option may be used to specify the field’s corresponding database column. If the column option is not specified, the field name will be used.

'email' => 'unique:users,email_address'

Custom Database Connection

Occasionally, you may need to set a custom connection for database queries made by the Validator. As seen above, setting unique:users as a validation rule will use the default database connection to query the database. To override this, specify the connection and the table name using «dot» syntax:

'email' => 'unique:connection.users,email_address'

Forcing A Unique Rule To Ignore A Given ID:

Sometimes, you may wish to ignore a given ID during the unique check. For example, consider an «update profile» screen that includes the user’s name, e-mail address, and location. You will probably want to verify that the e-mail address is unique. However, if the user only changes the name field and not the e-mail field, you do not want a validation error to be thrown because the user is already the owner of the e-mail address.

To instruct the validator to ignore the user’s ID, we’ll use the Rule class to fluently define the rule. In this example, we’ll also specify the validation rules as an array instead of using the | character to delimit the rules:

use IlluminateValidationRule;

Validator::make($data, [
    'email' => [
        'required',
        Rule::unique('users')->ignore($user->id),
    ],
]);

{note} You should never pass any user controlled request input into the ignore method. Instead, you should only pass a system generated unique ID such as an auto-incrementing ID or UUID from an Eloquent model instance. Otherwise, your application will be vulnerable to an SQL injection attack.

Instead of passing the model key’s value to the ignore method, you may pass the entire model instance. Laravel will automatically extract the key from the model:

Rule::unique('users')->ignore($user)

If your table uses a primary key column name other than id, you may specify the name of the column when calling the ignore method:

Rule::unique('users')->ignore($user->id, 'user_id')

By default, the unique rule will check the uniqueness of the column matching the name of the attribute being validated. However, you may pass a different column name as the second argument to the unique method:

Rule::unique('users', 'email_address')->ignore($user->id),

Adding Additional Where Clauses:

You may also specify additional query constraints by customizing the query using the where method. For example, let’s add a constraint that verifies the account_id is 1:

'email' => Rule::unique('users')->where(function ($query) {
    return $query->where('account_id', 1);
})

url

The field under validation must be a valid URL.

uuid

The field under validation must be a valid RFC 4122 (version 1, 3, 4, or 5) universally unique identifier (UUID).

Conditionally Adding Rules

Validating When Present

In some situations, you may wish to run validation checks against a field only if that field is present in the input array. To quickly accomplish this, add the sometimes rule to your rule list:

$v = Validator::make($data, [
    'email' => 'sometimes|required|email',
]);

In the example above, the email field will only be validated if it is present in the $data array.

{tip} If you are attempting to validate a field that should always be present but may be empty, check out this note on optional fields

Complex Conditional Validation

Sometimes you may wish to add validation rules based on more complex conditional logic. For example, you may wish to require a given field only if another field has a greater value than 100. Or, you may need two fields to have a given value only when another field is present. Adding these validation rules doesn’t have to be a pain. First, create a Validator instance with your static rules that never change:

$v = Validator::make($data, [
    'email' => 'required|email',
    'games' => 'required|numeric',
]);

Let’s assume our web application is for game collectors. If a game collector registers with our application and they own more than 100 games, we want them to explain why they own so many games. For example, perhaps they run a game resale shop, or maybe they just enjoy collecting. To conditionally add this requirement, we can use the sometimes method on the Validator instance.

$v->sometimes('reason', 'required|max:500', function ($input) {
    return $input->games >= 100;
});

The first argument passed to the sometimes method is the name of the field we are conditionally validating. The second argument is the rules we want to add. If the Closure passed as the third argument returns true, the rules will be added. This method makes it a breeze to build complex conditional validations. You may even add conditional validations for several fields at once:

$v->sometimes(['reason', 'cost'], 'required', function ($input) {
    return $input->games >= 100;
});

{tip} The $input parameter passed to your Closure will be an instance of IlluminateSupportFluent and may be used to access your input and files.

Validating Arrays

Validating array based form input fields doesn’t have to be a pain. You may use «dot notation» to validate attributes within an array. For example, if the incoming HTTP request contains a photos[profile] field, you may validate it like so:

$validator = Validator::make($request->all(), [
    'photos.profile' => 'required|image',
]);

You may also validate each element of an array. For example, to validate that each e-mail in a given array input field is unique, you may do the following:

$validator = Validator::make($request->all(), [
    'person.*.email' => 'email|unique:users',
    'person.*.first_name' => 'required_with:person.*.last_name',
]);

Likewise, you may use the * character when specifying your validation messages in your language files, making it a breeze to use a single validation message for array based fields:

'custom' => [
    'person.*.email' => [
        'unique' => 'Each person must have a unique e-mail address',
    ]
],

Custom Validation Rules

Using Rule Objects

Laravel provides a variety of helpful validation rules; however, you may wish to specify some of your own. One method of registering custom validation rules is using rule objects. To generate a new rule object, you may use the make:rule Artisan command. Let’s use this command to generate a rule that verifies a string is uppercase. Laravel will place the new rule in the app/Rules directory:

php artisan make:rule Uppercase

Once the rule has been created, we are ready to define its behavior. A rule object contains two methods: passes and message. The passes method receives the attribute value and name, and should return true or false depending on whether the attribute value is valid or not. The message method should return the validation error message that should be used when validation fails:

<?php

namespace AppRules;

use IlluminateContractsValidationRule;

class Uppercase implements Rule
{
    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        return strtoupper($value) === $value;
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'The :attribute must be uppercase.';
    }
}

You may call the trans helper from your message method if you would like to return an error message from your translation files:

/**
 * Get the validation error message.
 *
 * @return string
 */
public function message()
{
    return trans('validation.uppercase');
}

Once the rule has been defined, you may attach it to a validator by passing an instance of the rule object with your other validation rules:

use AppRulesUppercase;

$request->validate([
    'name' => ['required', 'string', new Uppercase],
]);

Using Closures

If you only need the functionality of a custom rule once throughout your application, you may use a Closure instead of a rule object. The Closure receives the attribute’s name, the attribute’s value, and a $fail callback that should be called if validation fails:

$validator = Validator::make($request->all(), [
    'title' => [
        'required',
        'max:255',
        function ($attribute, $value, $fail) {
            if ($value === 'foo') {
                $fail($attribute.' is invalid.');
            }
        },
    ],
]);

Using Extensions

Another method of registering custom validation rules is using the extend method on the Validator facade. Let’s use this method within a service provider to register a custom validation rule:

<?php

namespace AppProviders;

use IlluminateSupportServiceProvider;
use IlluminateSupportFacadesValidator;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Validator::extend('foo', function ($attribute, $value, $parameters, $validator) {
            return $value == 'foo';
        });
    }
}

The custom validator Closure receives four arguments: the name of the $attribute being validated, the $value of the attribute, an array of $parameters passed to the rule, and the Validator instance.

You may also pass a class and method to the extend method instead of a Closure:

Validator::extend('foo', 'FooValidator@validate');

Defining The Error Message

You will also need to define an error message for your custom rule. You can do so either using an inline custom message array or by adding an entry in the validation language file. This message should be placed in the first level of the array, not within the custom array, which is only for attribute-specific error messages:

"foo" => "Your input was invalid!",

"accepted" => "The :attribute must be accepted.",

// The rest of the validation error messages...

When creating a custom validation rule, you may sometimes need to define custom placeholder replacements for error messages. You may do so by creating a custom Validator as described above then making a call to the replacer method on the Validator facade. You may do this within the boot method of a service provider:

/**
 * Bootstrap any application services.
 *
 * @return void
 */
public function boot()
{
    Validator::extend(...);

    Validator::replacer('foo', function ($message, $attribute, $rule, $parameters) {
        return str_replace(...);
    });
}

Implicit Extensions

By default, when an attribute being validated is not present or contains an empty string, normal validation rules, including custom extensions, are not run. For example, the unique rule will not be run against an empty string:

$rules = ['name' => 'unique:users,name'];

$input = ['name' => ''];

Validator::make($input, $rules)->passes(); // true

For a rule to run even when an attribute is empty, the rule must imply that the attribute is required. To create such an «implicit» extension, use the Validator::extendImplicit() method:

Validator::extendImplicit('foo', function ($attribute, $value, $parameters, $validator) {
    return $value == 'foo';
});

{note} An «implicit» extension only implies that the attribute is required. Whether it actually invalidates a missing or empty attribute is up to you.

Implicit Rule Objects

If you would like a rule object to run when an attribute is empty, you should implement the IlluminateContractsValidationImplicitRule interface. This interface serves as a «marker interface» for the validator; therefore, it does not contain any methods you need to implement.

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Вывод ошибок php docker
  • Вывод ошибок php ajax