laravel 数据验证规则详解(2)

简单例子

return [
  'title.required' => 'A title is required',
  'body.required' => 'A message is required',
  'avatar' => [
    'required',
    Rule::dimensions()->maxWidth(500)->maxHeight(250)->ratio(3/2), //限制图片大小和比例
  ],
  'foo.*.id' =>'distinct', //不允许重复
  'state' =>'exists:states', //指定表
  'state1' => 'exists:states,abbreviation', //指定表和字段
  'email' => 'exists:connection.staff,email', //指定查询的数据库
  'email1' => [
    'required',
    Rule::exists('staff')->where(function ($query){
      $query->where('account_id',1);
    }),
  ],
  'zones' => [
    'required',
    Rule::in(['first-zone','second-zone']),
  ],
  'video' => 'mimetypes:video/avi,video/mpeg,video/quicktime',
  'photo' => 'mimes:jpeg,bmp,png', //验证文件扩展名,规则上也会验证文件的MIME类型,通过读取文件的内容以猜测它的MIME类型
  'toppings' => [
    'required',
    Rule::notIn(['sprinkles','cherries']),
  ],
  //当使用regex时,必须使用数组,而不是|分隔符,特别是正则中有|时
  'email2' => 'unique:users,email_address',
  'email3' => 'unique:connection.users,email_address', //指定数据库
  'email4' => Rule::unique('users')->where(function ($query){
    $query->where('account_id',1);
  }),
  'custom' => [
    'person.*.email' => [
      'unique' => 'each person must have a unique e-mail address',
    ]
  ],
];

特殊例子

//验证时忽视id
Validator::make($data,[
  'email' => [
    'required',
    Rule::unique('users')->ignore($user->id,'user_id'),
  ]
]);

//在某些情况下,只有在该字段存在于输入数组中时,才可以对字段执行验证检查
$v = Validator::make($data,[
  'email' => 'sometimes|required|email',//email只有在data数组中时才会被验证
]);

$z = Validator::make($data,[
  'email' => 'required|email',
  'games' => 'required|numeric',
]);
$z->sometimes('reason','required|max:500',function ($input){
  return $input->games >= 100; //当值超过100时,reson才必填
});
$z->sometimes(['reson','cost'],'required',function ($input){
  return $input->games >= 100;
});
$validator = Validator::make($request->all(),[
  'photos.profile' => 'required|image',//验证数组中的某个key的值
]);

$validator = Validator::make($request->all(),[
  'person.*.email' => 'email|unique:users',
  'person.*.first_name' => 'required_with:person.*.last_name',
]);//验证指定数组输入字段中的每一个email都是唯一的

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

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

if ($validator->fails()){

}

$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')){

}
      

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/4063.html