Would like to check I have made a CustomValidator.php to handle all my additional validation rules but the problem is how should I return the custom error messages? This is how i did for my CustomValidator.php file,
<?php namespace App\Validators\CustomValidator;
use Illuminate\Validation\Validator;
use Auth;
class CustomValidator extends Validator
{
public function validateVerifyPassword($attribute, $value, $parameters)
{
$currentUser = Auth::user();
$credentials = array ('email' => $currentUser->email, 'password' => $currentUser->password);
return Auth::validate($credentials);
}
protected function replaceVerifyPassword($message, $attribute, $rule, $parameters)
{
return str_replace($attribute, $parameters[0], $message);
}
}
and this is how I define my custom error message in FormRequest.php
public function messages()
{
return [
'login_email.required' => 'Email cannot be blank',
'old_password.required' => 'You need to provide your current password',
'old_password.between' => 'Your current password must be between :min and :max characters',
'old_password.verifyPassword' => 'Invalid password',
'password.required' => 'Password is required.',
'password.between' => 'Your password must be between :min and :max characters',
'password_confirmation.required' => 'You need to retype your password',
'password_confirmation.same' => 'Your new password input do not match',
'g-recaptcha-response.required' => 'Are you a robot?',
'g-recaptcha-response.captcha' => 'Captcha session timeout'
];
}
Noted that the validation part is working, only it would not pass the custom error message and it return me with an error of
CustomValidator.php line 18:
Undefined offset: 0
which is at the $parameter[0]
part
Found out the solution to this, apparently when you try to execute the validation, the error message it appears will carry the key to that validation rule's error message. We use the image below as an example,
Notice that under the email field, there is an error message
validation.current_email
error, thecurrent_email
is the key to be used to specify your custom error message in the FormRequest. So basically what you do is in my FormRequest.php, I added the error messages like such:And this would be the final outcome in below image: