I am trying to add a custom validation message using the below code,
$validator = Validator::make(
$user,
[
'first_name' => 'required|min:2',
'email' => [
'required',
'email',
Rule::notIn(array_column(Customer::getEmails(), 'email'))
]
],
['email.required' => 'Email is required (Custom message)']);
I have added a custom message for email required validation. No issues there.
For Rule::notIn validation, currently it is returning The email is invalid. How can I add a custom message in this case?
Unable to find anything related in Laravel docs about this.
Try this:
$validator = Validator::make(
$user,
[
'first_name' => 'required|min:2',
'email' => [
'required',
'email',
Rule::notIn(array_column(Customer::getEmails(), 'email'))
]
],
[
'email.required' => 'Email is required (Custom message)',
'email.email' => 'Your custom message here',
'email.not_in' => 'Your custom message here',
]
);
Related
I am working on a registration form with Laravel 8 and Sanctum.
I have this piece of code in the AuthController to validate the form fields:
public function register(Request $request) {
$fields = $request->validate([
'first_name' => 'required|string,',
'last_name' => 'required|string',
'email' => 'required|string|unique:users,email',
'password' => 'required|string|confirmed',
'accept' => 'accepted',
]);
// More code here
}
I want to display more user-friendly validation error messages.
Rather than changing the validation.php file (resources\lang\en\validation.php), I want to change the set them for the registration form only, in the method above.
The problem
As someone that has used Codeigniter for a long time, I had, in Codeigniter, the posibility to do just that:
$this->form_validation->set_rules('first_name', 'First name', 'required', array('required' => 'The "First name" field is required'));
I was unable to do something similar in Laravel 8.
How do I get the desired result in Laravel 8?
Maybe this can work for ya.
$rules = [
'first_name' => 'required|string,',
'last_name' => 'required|string',
'email' => 'required|string|unique:users,email',
'password' => 'required|string|confirmed',
'accept' => 'accepted'
];
$customMessages = [
'required' => 'The :attribute field is required.'
];
$this->validate($request, $rules, $customMessages);
Also check out the laravel customizing error messages documentation.
The validate function excepts 3 parameters. A) request, B) the rules, C) Custome Messages.
$this->validate($request, $rules, $customMessages); It means define your custom Message Array by key value. Key is the rulename like require. For example:
[
'required' => 'The :attribute is really,really, really required if you use Login!'
'email.required' => 'Without email you dont come in ;-)'
]
Here my code :
$rules = [
'name' => 'required|string|max:255',
'price' => 'required|numeric|min:0',
'unit' => 'required|in:piece,kg,m',
'price_type' =>'required|string',
'service' => [
'string',
'required',
Rule::in($services_ids->all()),
],
'facility' => [
'string',
'required',
Rule::in($facilities_ids->all()),
],
'conciergeries' => [
'array',
'required',
Rule::in($conciergeries_ids->all()),
],
];
$custom_messages = [
'required' => 'Vous devez sélectionner un(e) :attribute.'
];
$validated = request()->validate($rules, $custom_messages);
The problem is that my custom_messages only works with 'name', 'price', 'unit', 'price_type' but not with 'service', 'facility' and 'conciergeries'.
Questions :
How to apply my custom messages with 'service', 'facility' and 'conciergeries' too ?
How to create a custom message for specifically one field ?
Thank's !
You just need to specify for which field you want to change the message
Try it like:-
$custom_messages = [
'service.required' => 'Your custom message for required service',
'service.string' => 'Your custom message of service should be string',];
And same process for facility and conciergeries.
I'm having a problem validating inputs that are only going to be present sometimes in the Request.
// Controller
public function update(Request $request, User $user)
{
$updateResult = $user->updateUser($request);
return dd($updateResult);
}
// User Model
protected $validation = [
'rules' => [
'email' => [
'sometimes',
'email',
'required',
],
'password' => [
'sometimes',
'min:6',
'required',
],
'first_name' => [
'sometimes',
'required',
],
'last_name' => [
'sometimes',
'required',
],
],
'messages' => [
'email.required' => 'An email is required.',
'email.email' => 'The email must be valid.',
'password.required' => 'A password is required.',
'password.min' => 'Your password must be at least six (6) characters long.',
'first_name.required' => 'Your first name is required.',
'last_name.required' => 'Your last name is required.',
],
];
public function updateUser(Request $request)
{
$validation = Validator::make($request->all(), [
$this->validation['rules'],
$this->validation['messages'],
]);
if ($validation->fails())
{
return $validation;
}
else
{
return "OK";
}
}
So in some update pages $request->all() is only going to have a subset of these fields. However, even a field is present, but the value is null, the required doesn't trigger.
[
'first_name' => null,
'last_name' => 'Davidson',
'job_title' => 'Tech Support',
]
The above request array will return "OK"... If I remove sometimes from the fields, then when a partial input request is sent, it fails saying the fields are required.
I am clearing missing something here, but from reading the docs I thought I'd configured this correctly:
In some situations, you may wish to run validation checks against a
field only if that field is present in the input array. To quickly
accomplish this, add the sometimes rule to your rule list:
$v = Validator::make($data, [
'email' => 'sometimes|required|email', ]);
The problem you are facing is simply due to an error in your call to the validator. The second parameter is not a multidimensional array as you passed. The rules array and the messages array are separate parameters.
$validation = Validator::make($request->all(), [
$this->validation['rules'],
$this->validation['messages'],
]);
Should be replaced by
$validation = Validator::make($request->all(),
$this->validation['rules'], $this->validation['messages']);
In Laravel 5.4 empty strings are converted to Null by the ConvertEmptyStringsToNull middleware... that might cause you some issues...
You should add nullable to all your optional validations...
Hope this helps
'first_name' => [
'sometimes',
'required',
],
Will never work as expected. Sometimes indicates: if something comes, what is the next rule? In this case 'required'. Required what? Change this to:
'first_name' => [
'sometimes',
'required',
'min:1',
],
The null value will still be a null value if no input is given and won't fail. If you want to keep the value of the field in the table for updates, populate the input in the form with it's respected values.
The null value was send as '' and got nulled by the ConvertEmptyStringsToNull::class in the app\Http\kernel.php middleware.
I have a validation rule as follows. I'm using the validate method via the ValidateRequests trait.
$this->validate($request, [
'entries' => 'required|max:5',
'entries.*.name' => 'required',
'entries.*.email' => 'required|email',
'entries.*.mobile_number' => 'required'
]);
And these are some sample error messages that I've encountered.
[
'entries.0.name' => ['The entries.0.name is required.'],
'entries.1.email' => ['The entries.1.email must be a valid email address.']
]
Is there a way to modify the message to these by using only the validation.php in modifying such messages?
[
'entries.0.name' => ['Line 0 - The name is required.'],
'entries.1.email' => ['Line 1 - The email must be a valid email address.']
]
If you want to customize the error message then you can do it as:
$validator = Validator::make($request->all(), [
'entries' => 'required|max:5',
'entries.*.name' => 'required',
'entries.*.email' => 'required|email',
'entries.*.mobile_number' => 'required'
]);
$validator->setAttributeNames([
'entries.*.name' => 'name',
'entries.*.email' => 'email',
'entries.*.mobile_number' => 'mobile number'
]);
$errors = $validation->errors()->all();
foreach ($errors as $key => $error) {
$errors[$key] = "Line {$key} - $error";
}
// dd($errors);
if($validation->fails()) {
return redirect()->back()->withErrors($errors());
}
Am using the Laravel Validator class to do some basic validation on an array.
My array :
$employee['name']='name';
$employee['address']='address';
$employee['department']['department_name']='deptname';
$employee['department']['department_address']='deptaddress';
I have the validation rules as below:
$rules = array(
'name'=> 'required',
'address' => 'required',
'department.department_name' => 'sometimes|required'
)
And the custom messages as below :
$messages = array(
'name.required' => 'Employee Name is required',
'address.required' => 'Address is required'
'department.department_name.required' => 'Department name is required'
)
I will use Validator::make($employee, $rules, $messages);
As per my rules, department_name should be validated if and only if it is present in the array. But currently the Validator is not validating department_name when its present and blank. Any ideas what I might be doing wrong?
You are going a bit wrong here see the docs here
it is mentioned there If I have $photos['profile'] then my validation will go like this
$validator = Validator::make($request->all(), [
'photos.profile' => 'required|image',
]);
From the above example, In your case it should be like this
$rules = array(
'name'=> 'required',
'address' => 'required',
'employee.department.department_name' => 'sometimes|required'
)
Since you have array like this $employee['department']['department_name']
So does the $message will go like this
$messages = array(
'name.required' => 'Employee Name is required',
'address.required' => 'Address is required'
'employee.department.department_name.required' => 'Department name is required'
)