使用laravel的表单验证器

1、使用默认的验证信息

  1. $rules = [
  2. 'phone' => 'required'
  3. ];
  4. $validator = Validator::make($request->all(), $rules);
  5. if ($validator->fails()) {
  6. $message = $validator->errors()->first();
  7. return new JsonResponse(['code' => '10501', 'msg' => $message, 'data' => []]);
  8. }

2、使用自定义的验证信息

  1. $rules = [
  2. 'phone' => 'required'
  3. ];
  4. $messages = [
  5. 'phone.required' => 'phone 是必填字段'
  6. ];
  7. $validator = Validator::make($request->all(), $rules, $messages);
  8. if ($validator->fails()) {
  9. $message = $validator->errors()->first();
  10. return new JsonResponse(['code' => '10501', 'msg' => $message, 'data' => []]);
  11. }


评论 0

发表评论

Top