1. 云栖社区>
  2. PHP教程>
  3. 正文

Validate (almost) anything in Laravel

作者:用户 来源:互联网 时间:2017-12-01 17:15:20

Validate (almost) anything in Laravel - 摘要: 本文讲的是Validate (almost) anything in Laravel, Laravel ships with some good validationcapabilties. Form request validationis a nice way to make sure http reques

Laravel ships with some good validationcapabilties. Form request validationis a nice way to make sure http requests pass valid data. To validate stuff that enters the application in some other way validators can be created manually.Unfortunately this is kinda verbose:

$validator = Validator::make(['myDate' => '201502028'], ['myDate' => 'date']);$isValidDate = ! $validator->fails();

We can do better than that by defining our own helper function:

/** * Validate some data. * * @param string|array $fields * @param string|array $rules * @return bool */function validate($fields, $rules){ if (! is_array($fields)) { $fields = ['default' => $fields]; } if (! is_array($rules)) { $rules = ['default' => $rules]; } return ! Validator::make($fields, $rules)->fails();}

Take a look at this Stack Overflow questionif you’re wondering where the function could be stored.

Once the function is loaded the validation from the previous example can be written like this:

validate('20150230', 'date'); //returns false validate('20150227', 'date'); //returns true

Nice, ‘n’ easy! Because the function hooks into Laravel’s validator almost anythingcan be validated:

validate('[email protected]', 'email'); //returns true validate('192.168.10.10', 'ip'); //returns true...

以上是云栖社区小编为您精心准备的的内容,在云栖社区的博客、问答、公众号、人物、课程等栏目也有的相关内容,欢迎继续使用右上角搜索按钮进行搜索,以便于您获取更多的相关知识。