I am trying to make the Validation fail. I have tried the following:
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');
}
The $validator->fails() goes true somehow and validation does not fail..
I have tried a solution like:
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);
It is Ugly as in View it always gives default error "unreal_input is required field". HELP!!
UPDATE
It was typo I used $messsages with 3 s
You changes are good so that you add
$rules['unreal_input']
and$messages['unreal_input.required']
However you are having a typo, See $messsages vs $messages. In one case there are 3x "s" other case there are only 2x so it is different array.