【问题标题】:Validation in Laravel 5.6Laravel 5.6 中的验证
【发布时间】:2018-12-11 08:01:30
【问题描述】:

这个问题已经问过了,但这并没有解决我的问题。

我尝试在我的laravel project 中使用验证。但它不起作用这是我的代码

$rules = array(
    'coupon_title'          => 'max:10',
    'coupon_type_id'        => 'numaric',
    'expiry_start_date'     => 'required|before_or_equal:expiry_end_date',
    'expiry_end_date'       => 'required',
);

$messages = [
    'before_or_equal'    => 'The :attribute must be smaller than the End Date',
    'before'    => 'The :attribute must be Greater than the Interview Start Date',
    'after'    => 'The :attribute must be Greater than the Interview End Date',
    'after_or_equal'    => 'The :attribute must be Greater than the Start Time',
    //'max' => 'asdasd'
];

$validator = Validator::make($request->all(), $rules, $messages);
if ($validator->fails()) 
{
    $messages = $validator->messages();
    return response()->json(['message'=>$messages],401);
}

在我的代码中,只有 expiry_start_date 字段经过验证。但 coupon_titlecoupon_type_id 字段未验证。

【问题讨论】:

  • 您在 coupon_type_id 附近有一个小错字:它是 'numeric',而不是 'numaric' ;)
  • coupon_title 和 coupon_type_id 是否允许为空?
  • @Virginia:Yes #coupon_title 允许空值
  • 您能否在使用这四个变量(coupon_title、coupon_type_id、expiry_start_date、expiry_end_date)的地方添加 HTML 部分/视图?我认为这可能更容易发现问题。
  • @Virginia:我设置了coupon_title Null 是的,看这张图片imgur.com/a/QLtZIW2

标签: php validation laravel-5.6


【解决方案1】:

您需要将numaric 拼写为numeric 并在验证规则中添加nullable 关键字

'coupon_title'          => 'string|max:10|nullable',
'coupon_type_id'        => 'numeric',

您还可以为numericmax 添加自定义消息

$messages = [
    'before_or_equal'    => 'The :attribute must be smaller than the End Date',
    'before'    => 'The :attribute must be Greater than the Interview Start Date',
    'after'    => 'The :attribute must be Greater than the Interview End Date',
    'after_or_equal'    => 'The :attribute must be Greater than the Start Time',
    'max' => 'The :attribute has crossed the limit',
    'numeric' => 'The :attribute must have numeric value'
];

【讨论】:

  • 工作,但我怀疑是否要将数据库中的字段更改为空?
  • @RameshS 是的,你需要在 mysql 中使列可以为空
猜你喜欢
  • 2019-01-07
  • 1970-01-01
  • 1970-01-01
  • 2018-12-09
  • 2019-02-12
  • 2018-11-13
  • 2019-01-17
  • 2019-02-28
  • 1970-01-01
相关资源
最近更新 更多