通过添加自定义错误在Laravel

时间:2017-09-10 16:19:55

标签: php forms laravel validation custom-errors

我试图让验证失败。我尝试过以下方法:

UserController.php

public function add_user(Request $request)
{
$messsages = array(
    'email.unique' => 'Email already exists',
    'email.required' => 'Email is missing',
    'valid_from.date_format' => 'Valid from date invalid. mm/dd/yyyy e.g. 12/13/2014',
    'valid_to.date_format' => 'Valid to date invalid. mm/dd/yyyy e.g. 12/13/2014',
    'valid_to.required' => 'Valid to date is missing',
    'cnic.min' => 'CNIC is 15 characters long. Do not forget hyphens 35212-XXXXXXX-X',
    'cnic.max' => 'CNIC is 15 characters long. Do not forget hyphens 35212-XXXXXXX-X',
    'cnic.regex' => 'CNIC include hyphens 35212-XXXXXXX-X'
);

$rules = array(
    'name' => 'required',
    'email' => 'required|email|unique:users',
    'valid_from' => 'required|date_format:m/d/Y',
    'valid_to' => 'required|date_format:m/d/Y',
    'phone' => 'numeric',
    'cnic' => [
    'min:15',
    'max:15',
    'regex:/\d{5}-\d{7}-\d{1}/'
    ]
);

$validator = Validator::make($request->all(), $rules, $messsages);

//Check year
$y_from = substr($request->valid_from, -4); $y_from = (int)$y_from;
$y_to = substr($request->valid_to, -4); $y_to = (int)$y_to;
if($y_from >= 2038 || $y_to >= 2038) //HERE I ADD CUSTOM ERROR
{
    $validator->getMessageBag()->add('maxyear', 'Invalid date. Maximum value of Year = 2038');
    //$validator->errors()->add('maxyear', 'Invalid date. Maximum value of Year = 2038'); //Doesnt work as above
}

if ($validator->fails()) { //DOESNT WORK
    $messages = $validator->messages();
    return Redirect::route('userAdd')->withErrors($messages);
}

$user = new User;
$user->name = $request->name;
/* Save other model data */

$user->save();
Session::flash('userCreated', 'User Created Successfully');

return redirect('/pending_users');
}

$ validator-> failed()以某种方式变为真,验证不会失败..

我尝试过像:

这样的解决方案
if($y_from >= 2038 || $y_to >= 2038)
{
    //$validator->getMessageBag()->add('maxyear', 'Invalid value for Year in date. Max year = 2038');
    //$validator->errors()->add('maxyear', 'Invalid date. Maximum value of Year = 2038');
    $rules['unreal_input'] = 'required'; 
    $messages['unreal_input.required'] = 'Invalid date. Maximum value of Year = 2038';
}

$validator = Validator::make($request->all(), $rules, $messsages);

它很丑陋,因为它总是提供默认错误“unreal_input is required field”。 HELP !!

更新

这是错字我使用$ messsages 3 s

1 个答案:

答案 0 :(得分:0)

您的更改很好,因此您可以添加$rules['unreal_input']$messages['unreal_input.required']

但是你有一个拼写错误,请参阅$ messsages vs $ messages。在一种情况下有3x“s”其他情况只有2x所以它是不同的数组。