Im using a form request for validation and want to customize my errors. since I have a lot of fields to validate,I want to know if it is possible to use the same error message for multiple fields that have the same validation rule.
My actual form request looks like :
class CreateServerRequest extends Request
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'srv_prefix' => 'required|regex:/^[A-Z][-_A-Z0-9]*$/',
//20 more to go...
];
}
public function messages()
{
return [
'srv_prefix.required' => 'required.',
'srv_prefix.regex' => 'nope, bad format.'
];
}
}
I dont like the idea of adding as many lines of errors as fields (some fields may have 2 validation rules..) is there any way to tell laravel if validation rule = required then show this type of error regardless of the field ?
You can use just the validation name as the key for the message array, if you want all messages for that particular validation to be the same:
public function messages()
{
return [
'required' => 'The field :attribute is required.',
'regex' => 'nope, bad format.'
];
}
You can use :attribute as a placeholder that will be replaced with the field name, if you need that to be part of the error message. The documentation for this is in the Validation Custom Error Messages section, not in the Form Request Validation one.
Related
I don't remember this is always been so freakin' hard to do in Laravel, but how to return back to form page blade.php instead of displaying the errors as JSON object on the browser?
Controller
public function create()
{
return view('view.to.form');
}
public function store(CreateModelRequest $request)
{
Model::create($request->validated());
}
// CreateModelRequest
protected function failedValidation(Validator $validator)
{
return back()->withErrors($validator);
}
I've tried countless other "solutions" as well, but no matter what,
the failed form request return raw JSON to the browser:
{
message: 'The given data was invalid',
errors: {
first_name: ['The first name field is required.'],
last_name: ['The last name field is required.'],
email: ['The email field is required.'],
},
}
}
Ok, I found one way to return back to the form but damn this is awful:
// Controller's store method
$validator = Validator::make($request->all(), [
// rules
]);
if ($validator->fails()) {
return back()->withErrors($validator->errors());
}
I'd like to extract that code into Request class but apparently we can't return a view and therefore we can't use them outside of API endpoints. Please, correct me if I'm wrong.
Currently in lumen when you use the $this->validate($request, $rules) function inside of a controller it will throw a ValidationException with error for your validation rules(if any fail of course).
However, I need to have a code for every validation rule. We can set custom messages for rules, but I need to add a unique code.
I know there's a "formatErrorsUsing" function, where you can pass a formatter. But the data returned by the passed argument to it, has already dropped the names of the rules that failed, and replaced them with their messages. I of course don't want to string check the message to determine the code that should go there.
I considered setting the message of all rules to be "CODE|This is the message" and parsing out the code, but this feels like a very hacked solution. There has to be a cleaner way right?
I've solved this for now with the following solution:
private function ruleToCode($rule) {
$map = [
'Required' => 1001,
];
if(isset($map[$rule])) {
return $map[$rule];
}
return $rule;
}
public function formatValidationErrors(Validator $validator) {
$errors = [];
foreach($validator->failed() as $field => $failed) {
foreach($failed as $rule => $params) {
$errors[] = [
'code' => $this->ruleToCode($rule),
'field' => $field,
];
}
}
return $errors;
}
My need is just Laravel validation Rules.I want to use Laravel validation to check variables. and show custom errors by returning string in controller.(I dont use view, blade, session,... I just return string)
if(strlen($username) < 4) return '{"r": "US","msg": "username is short"}';
if(strlen($username) > 64) return '{"r": "UL","msg": "username is long"}';
if(strlen($address) > 200) return '{"r": "A","msg": "wrong address"}';
I want something like this:
if($validation->username->min has error)
return 'string:username is short';
if($validation->address->max has error)
return 'string:address is long';
if($validation->username->unique has error)
return 'string:username already exists';
Have a look at the official documentation of validation in Laravel. You don't have to handle every case manually. Validator::make() will generate a validator object for you. The first parameter will take your data as an associative array. The second argument will define all rules as desired. As a third, optional parameter you may define alternative error messages if you don't like the default ones. The will be returned in the errors() method in case something isn't valid.
$validator = Validator::make($yourDataArray, [
'username' => 'min:4|max:64|exists:table,username',
'address' => 'max:64'
], [
'min' => ':attribute is too short.',
'exists' => ':attribute already exists.
]);
if ($validator->fails()) {
return $validator->errors()->all();
}
If you don't want to get an array with all errors at once, you can get the state of each field like so:
if ($validator->errors()->has('username')) { // Username field is invalid
return $validator->errors()->first('username'); // Get the first error
}
And if you want to know what rule exactly failed, you can use something like that:
if(isset($validator->failed()['username']['Max'])) {
return 'Username is too long.';
}
I am learning/using Laravel5 and using the Request generator tool to make a custom request validation handler;
php artisan make:request <nameOfRequestFile>
And I find that my validation always passes, but I don't know why.
On my view I do a vardump of the errors;
{{ var_dump($errors) }}
And when I submit an empty form it always inserts a new record, when it should fail.
The var dump reports;
object(Illuminate\Support\ViewErrorBag)#135 (1) { ["bags":protected]=> array(0) { } }
Which seems to suggest the error bag is always empty.
My request file is pretty simple
namespace App\Http\Requests;
use App\Http\Requests\Request;
class PublishDriverRequest extends Request
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'name.required|min:3' => 'Please provide a name.',
'companyName.required|min:3' => 'Please provide a company name.'
];
}
}
I checked my input form and the names are the same;
<input type="text" name="name" id="name" class="form-control">
<input type="text" name="companyName" id="companyName" class="form-control">
And I checked my database, the names are the same too.
My controller when storing the data is equally straight forward;
public function store(PublishDriverRequest $request) {
Driver::create($request->all());
return redirect('/');
}
So I'm not sure why the validation always passes; if I submit an empty form it should fail as the rules indicate minimum length and required.
What am I doing wrong?
Change you validation rules to:
public function rules()
{
return [
'name' => 'required|min:3',
'companyName' => 'required|min:3',
];
}
To show custom validation error:
public function messages()
{
return [
'name.required' => 'Please provide a name.',
'companyName.required' => 'Please provide a company name.',
];
}
Note: Use message() method before rules()
I want to validate alpha_dash(Alphabets and Spaces) and the code below works fine
Validator::extend('alpha_spaces', function($attribute, $value)
{
return preg_match("/^[a-z0-9 .\-]+$/i", $value);
});
but the error it gives is not user friendly :
validation.alpha_spaces
How can change this message?
This is the method where it is posts
public function create(Request $request)
{
$this->validate($request, [
'title' => 'required|alpha_spaces|max:255',
]);
}
Thanks!
Just add your custom error message as an array element to resources/lang/xx/validation.php:
'alpha_spaces' => 'The :attribute may only contain letters, numbers and spaces.',
Read more: http://laravel.com/docs/5.0/validation#custom-error-messages