在 Laravel 5.6 中验证

Validation in 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);
}

In my code only expiry_start_date field validated. But coupon_title and coupon_type_id fields not validated.

您需要将拼写 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'
];