教程 > laravel 教程 > 阅读:740

laravel 验证规则——迹忆客-ag捕鱼王app官网

目录


自带的验证规则

以下是所有可用的验证规则及其功能的列表

accepted

验证中的字段必须为yes,on,1或true。这对于验证是否接受“服务条款”这种场景很有用。

active_url

根据php函数dns_get_record函数,验证中的字段必须具有有效的a或aaaa记录。url的主机名在传递个dns_get_record函数之前需要先有parse_url函数进行提取。

after:date

验证下的字段必须是给定日期之后的值。日期将被传递到strtotimephp函数中:

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

可以指定另一个字段与日期进行比较,而不用传递一个date字符串个给strtotime函数串:

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

after_or_equal:date

验证中的字段必须是晚于或等于给定日期的值

alpha

验证中的字段必须完全是字母字符。

alpha_dash

验证中的字段可能包含字母数字字符以及破折号和下划线。

alpha_num

验证中的字段必须完全是字母数字字符。

array

验证中的字段必须为php array。

bail

第一次验证失败后,停止运行验证规则。

before:date

验证中的字段必须是给定日期之前的值。

before_or_equal:date

验证中的字段必须是早于或等于给定日期的值。

between:min,max

验证中的字段的大小必须介于给定的min和max之间。

boolean

验证中的字段必须能够转换为布尔值。

confirmed

验证中的字段必须具有一个对其进行确认的字段foo_confirmation。例如,如果正在验证的字段为password,password_confirmation则输入中必须存在匹配的字段。

date

验证中的字段必须为有效的日期。

date_equals:date

验证中的字段必须等于给定的日期。

date_format:format

验证中的字段必须匹配给定的格式。

different:field

验证中的字段必须具有不同于field的值。

digits:value

验证中的字段必须为数字,并且必须具有精确的value长度。

digits_between:min,max

验证中的字段必须为数字,并且长度必须介于给定的min和max之间。

dimensions

验证中的文件必须是满足规则参数指定的尺寸限制的图像:

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

可用的约束为:minwidthmaxwidthminheightmaxheightwidthheightratio

ratio 的值是用宽度除以高度得来的。可以通过类似与3/2,或者float数值(如1.5)来指定:

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

由于此规则需要几个参数,因此我们可以使用rule::dimensions方法来构建规则:

use illuminate\validation\rule;
validator::make($data, [
    'avatar' => [
        'required',
        rule::dimensions()->maxwidth(1000)->maxheight(500)->ratio(3 / 2),
    ],
]);

distinct

使用数组时,验证下的字段不得包含任何重复的值。

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

email

验证下的字段必须格式化为电子邮件地址。在后台,此验证规则利用egulias/email-validator来验证电子邮件地址。默认使用rfcvalidation验证器,但也可以应用其他验证样式:

'email' => 'email:rfc,dns'

上面的示例将应用rfcvalidationdnscheckvalidation验证。下面是可以应用的验证样式的完整列表:

  • rfc: rfcvalidation
  • strict: norfcwarningsvalidation
  • dns: dnscheckvalidation
  • spoof: spoofcheckvalidation
  • filter: filteremailvalidation

endswith:foo,bar,...

验证中的字段必须以给定值之一结尾。

exclude_if:anotherfield,value

如果anotherfield字段等于value,则正在验证的字段将从validatevalidated方法返回的请求数据中排除。

exclude_unless:anotherfield,value

除非anotherfield的字段等于value,否则正在验证的字段将从validate和validated方法返回的请求数据中排除。

exists:table,column

验证的字段必须存在于给定的数据库表上。

'state' => 'exists:states'

如果column未指定该选项,则将使用字段名称。

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

有时,我们可能需要指定用于exists查询的特定数据库连接。可以通过使用“ .”语法在连接名之前添加表名来完成此操作:

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

可以指定用来确定表名的eloquent模型,而不是直接指定表名:

'user_id' => 'exists:app\user,id'

如果要定制验证规则执行的查询,则可以使用rule类来流畅地定义规则。在此示例中,我们还将验证规则指定为数组,而不是使用|字符来分隔它们:

use illuminate\validation\rule;
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或webp)

in:foo,bar,...

验证下的字段必须包含在给定的值列表中。由于此规则通常需要将数组进行指定分隔符连接,因此可以使用rule::in方法来流畅地构建规则:

use illuminate\validation\rule;
validator::make($data, [
    'zones' => [
        'required',
        rule::in(['first-zone', 'second-zone']),
    ],
]);

in_array:anotherfield.*

验证中的字段必须存在于anotherfield的值中。

integer

验证中的字段必须为整数。

ip

验证下的字段必须是ip地址。

ipv4

验证中的字段必须是ipv4地址。

ipv6

验证中的字段必须是ipv6地址。

json

验证中的字段必须是有效的json字符串。

lt:field

验证中的字段必须小于给定的字段。这两个字段必须具有相同的类型。

lte:field

验证中的字段必须小于或等于给定的字段。这两个字段必须具有相同的类型。

max:value

待验证的字段必须小于或等于指定的value。

mimetypes:text/plain,...

验证中的文件必须与给定的mime类型之一匹配:

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

mimes:foo,bar,...

验证中的文件必须具有与列出的扩展名之一相对应的mime类型。

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

min:value

待验证的字段不能小于指定的value值。

not_in:foo,bar,...

验证中的字段不得包含在给定的值列表中。可以使用 rule::notin 方法

use illuminate\validation\rule;
validator::make($data, [
    'toppings' => [
        'required',
        rule::notin(['sprinkles', 'cherries']),
    ],
]);

not_regex:pattern

验证中的字段不得与给定的正则表达式匹配。

nullable

验证中的字段可能是null。

numeric

验证下的字段必须为数字。

password

验证下的字段必须与经过身份验证的用户密码匹配。

'password' => 'password:api'

present

验证中的字段必须存在于输入数据中,但可以为空。

regex:pattern

验证中的字段必须匹配给定的正则表达式

required

验证中的字段必须存在于输入数据中,并且不能为空。如果满足以下条件之一,则该字段被视为“空”:

  • 值是null。
  • 该值是一个空字符串。
  • 该值是一个空数组或空countable对象。
  • 该值是没有路径的上载文件。

required_if:anotherfield,value,...

如果anotherfield字段等于指定的任意value,则正在验证的字段必须存在且不能为空。

如果想为required_if规则构造一个更复杂的条件,则可以使用rule::requiredif方法。

use illuminate\validation\rule;
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,...

除非anotherfield字段等于 指定的任意value,否则正在验证的字段必须存在且不能为空。

required_with:foo,bar,...

仅当存在任何其他指定的字段时,验证下的字段必须存在且不为空。

required_with_all:foo,bar,...

仅当所有其他指定的字段都存在时,验证中的字段必须存在且不为空。

required_without:foo,bar,...

仅当不存在任何其他指定字段时,验证下的字段必须存在且不为空。

required_without_all:foo,bar,...

仅当所有其他指定的字段都不存在时,验证中的字段必须存在且不为空。

same:field

给定的字段必须与正在验证的字段匹配。

size:value

验证中的字段必须具有与给定值匹配的大小。对于字符串,则value是字符串中的字符个数;对于数字,则value是值的大小;对于数组,value则是元素的个数。

// validate that a string is exactly 12 characters long...
'title' => 'size:12';
// validate that a provided integer equals 10...
'seats' => 'integer|size:10';
// validate that an array has exactly 5 elements...
'tags' => 'array|size:5';
// validate that an uploaded file is exactly 512 kilobytes...
'image' => 'file|size:512';

starts_with:foo,bar,...

验证中的字段必须以给定值之一开头。

string

验证中的字段必须为字符串。

timezone

验证中的字段必须是有效的时区标识符。

unique:table,column,except,idcolumn

验证中的字段在给定的数据库表中一定不能存在。

可以指定用来确定表名的eloquent模型,而不是直接指定表名:

'email' => 'unique:app\user,email_address'

column选项可用于指定字段的对应数据库列。如果column未指定该选项,则将使用字段名称。

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

有时,我们可能需要为validator进行的数据库查询设置自定义连接。

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

url

验证下的字段必须是有效的url。

uuid

验证中的字段必须是有效的rfc 4122(版本1、3、4或5)通用唯一标识符(uuid)。


自定义验证规则

使用规则对象

laravel提供了多种有用的验证规则;但是,我们可能希望自己指定一些规则。注册自定义验证规则的一种方法是使用规则对象。要生成新的规则对象,可以使用artisan命令make:rule。让我们使用此命令来生成一个验证字符串是否为大写的规则。laravel会将新规则放置在app/rules目录中:

$ php artisan make:rule uppercase

创建规则后,我们就可以定义其行为了。规则对象包含两个方法:passesmessagepasses方法接收属性值和名称,并根据属性值是否有效来返回true或false。message方法返回验证失败时应使用的验证错误消息:

如果我们想从translation 文件中返回错误消息,则可以从message方法中调用trans帮助函数:

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

定义规则后,您可以通过将规则对象的实例与其他验证规则一起传递给验证器:

use app\rules\uppercase;
$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.');
            }
        },
    ],
]);

使用扩展

注册自定义验证规则的另一种方法是使用validator facadeextend方法。让我们在service provider中使用此方法来注册自定义验证规则:

定制验证程序closure接收四个参数:

  • $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...

创建自定义验证规则时,有时可能需要为错误消息定义自定义占位符。我们可以通过如上所述创建的自定义验证程序,然后通过调用validator facadereplacer方法来实现。我们可以在service providerboot方法中执行此操作:

/**
 * 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';
});

“隐式”扩展名仅表示该属性是必需的。它是否实际上使缺少的属性或空的属性无效取决于我们的判断。

隐式规则对象

如果希望在属性为空时运行规则对象,则应实现illuminate\contracts\validation\implicitrule接口。该接口用作验证程序的“标记接口”。因此,它不包含您需要实现的任何方法。

查看笔记

扫码一下
查看教程更方便
网站地图