Laravel 5.6中的验证

时间:2018-12-11 08:01:31

标签: php validation laravel-5.6

这个问题已经问了,但是不能解决我的问题。

我尝试在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字段未通过验证。

1 个答案:

答案 0 :(得分: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'
];