check if validation fails (with custom mesages) - laravel

When using the validation like below with custom messages how is possible to check if the validation fails?
$rules = [
'email' => 'required|email'
];
$customMessages = [
'email.required' => 'The email is required.',
'email.email' => 'Please insert a valid email.'
];
$this->validate($request, $rules, $customMessages);
Like below, without custom messages is possible to use $validator->fails() but in the above case how to verify if the validation fails?
$validator = Validator::make($request->all(), [
//...
]);
if ($validator->fails()) {
//...
}

When you use $this->validate it validate your request against your validation rules and if failed then it redirect to previous page with validation message. If you want to use $validator->fails() then use Validator::make with custom message. Like this
$rules = [
'email' => 'required|email'
];
$customMessages = [
'email.required' => 'The email is required.',
'email.email' => 'Please insert a valid email.'
];
$validator = Validator::make($request->all(), $rules, $customMessages);
if ($validator->fails()) {
//...
}
Check validator make method https://laravel.com/api/5.0/Illuminate/Validation/Factory.html#method_make

much simpler solution is to use custom handler in app\Exceptions\Handler.php:
public function register()
{
$this->renderable(function (ValidationException $e, $request) {
//list of specific failed tests
$e->validator->failed();
return response()->json(['message' => 'custom message','meow'=>'meow',$e->status);
});
}
this way you keep old behavior AND can still change messages sent back to the user/frontend

Related

Laravel Custom Validation - Mailgun API

I'm trying to implement one of Laravel's new features "Custom Validation Rules" and I'm running into the following error:
Object of class Illuminate\Validation\Validator could not be converted to string
I'm following the steps in this video:
New in Laravel 5.5: Project: Custom validation rule classes (10/14)
It's an attempt Mailgun API's Email Validation tool.
Simple form that requests: first name, last name, company, email and message
Here is my code:
web.php
Route::post('contact', 'StaticPageController#postContact');
StaticPageController.php
use Validator;
use App\Http\Validation\ValidEmail as ValidEmail;
public function postContact(Request $request) {
return Validator::make($request->all(), [
'firstname' => 'required|max:90',
'lastname' => 'required|max:120',
'company' => 'max:120',
'email' => [
'required', 'string', 'max:255',
new ValidEmail(new \GuzzleHttp\Client)
],
'message' => 'required',
]);
}
ValidEmail.php
<?php
namespace App\Http\Validation;
use Illuminate\Contracts\Validation\Rule;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Client as Guzzle;
class ValidEmail implements Rule
{
protected $client;
protected $message = 'Sorry, invalid email address.';
public function __construct(Guzzle $client)
{
$this->client = $client;
}
public function passes($attribute, $value)
{
$response = $this->getMailgunResponse($value);
}
public function message()
{
return $this->message;
}
protected function getMailgunResponse($address)
{
$request = $this->client->request('GET', 'https://api.mailgun.net/v3/address/validate', [
'query' => [
'api_key' => env('MAILGUN_KEY'),
'address' => $address
]
]);
dd(json_decode($request->getBody()));
}
}
Expectation
I'm expecting to see something like this:
{
+"address": "test#e2.com"
+"did_you_mean": null
+"is_disposable_address": false
+"is_role_address": false
+"is_valid": false
+"parts": {
...
}
}
Any help is much appreciated. I've been trying to get this simple example to work for over two hours now. Hopefully someone with my experience can help!
In your controller
Try this:
$validator = Validator::make($request->all(), [
'firstname' => 'required|max:90',
'lastname' => 'required|max:120',
'company' => 'max:120',
'email' => [
'required', 'string', 'max:255',
new ValidEmail(new \GuzzleHttp\Client)
],
'message' => 'required',
]);
if ($validator->fails()) {
return redirect()->back()
->withErrors($validator)
->withInput();
}
// if valid ...
According to your route, the postContact method is the method to handle the route. That means the return value of this method should be the response you want to see.
You are returning a Validator object, and then Laravel is attempting to convert that to a string for the response. Validator objects cannot be converted to strings.
You need to do the validation, and then return the correct response based on that validation. You can read more about manual validators in the documenation here.
In short, you need something like this:
public function postContact(Request $request) {
$validator = Validator::make($request->all(), [
'firstname' => 'required|max:90',
'lastname' => 'required|max:120',
'company' => 'max:120',
'email' => [
'required', 'string', 'max:255',
new ValidEmail(new \GuzzleHttp\Client)
],
'message' => 'required',
]);
// do your validation
if ($validator->fails()) {
// return your response for failed validation
}
// return your response on successful validation
}

Custom Validation Laravel multiple attributes 5.5

In my form I have 2 attributes that need to be unique, I am trying to use Laravels Validator to do this but am very stuck..
Even if i add a return false/true to the function, there are no errors generated and the controller continues on. Am I missing something (not according to their docs :| )
$validator = Validator::make($request->all(), [
'organisationid' => 'required',
'membershipcode' => 'required'
]);
$validator->sometimes('membershipcode', 'required', function($input) {
return false;
});
In the store method in your controller, you can add validation like this:
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required|unique',
'description' => 'required',
]);
$movie = Model::create($request->all());
return redirect('view')->with('message', 'Added successfully');
}
The available validation rules are here: https://laravel.com/docs/5.5/validation#available-validation-rules

Toastr notification on failed form submit

I'm using toastr notification in my app. I send the notification when the form submit is failed due to validation or when the form submit is succeed. I usually do it this way :
public function store(Request $request) {
$data = $request->all();
$rules = [
'name' => 'required|string',
'email' => 'required|email',
'message' => 'required|string',
'g-recaptcha-response' => 'required|captcha',
];
$validate = Validator::make($data, $rules);
if ($validate->fails()) {
$error = array(
'message' => "Error sending the message!",
'alert-type' => 'error'
);
return back()->withErrors($validate)->withInput()->with($error);
}
Feedback::create($data);
$success = array(
'message' => "Thanks for the feedback! Your message was sent successfully!",
'alert-type' => 'success'
);
return redirect()->route('contactus')->with($success);
}
But when the table columns number is large (10 columns or more) I'd like to use Form Request Class instead rather than declaring the rules in the store method. So it became like this :
public function store(FeedbackRequest $request) {
$data = $request->all();
Feedback::create($data);
$success = array(
'message' => "Thanks for the feedback! Your message was sent successfully!",
'alert-type' => 'success'
);
return redirect()->route('contactus')->with($success);
}
The problem is, when using Form Request I don't know how to send the error notification when validation fails. Is there a way to check if Form Request Class validation failed so I can send the error notification ? That's all and thanks!
Adding After Hooks To Form Requests is exactly what you need in your Request class:
public function withValidator($validator)
{
$validator->after(function ($validator) {
if ($validator->failed()) {
$validator->errors()->add('field', 'Something is wrong with this field!'); // handle your new error message here
}
});
}

email validation not working in update form using laravel validation

$id = $request->id;
$validation = Validator::make($request->all(), [
'email' => 'unique:customers,email,'.$request->id
]);
You're using a custom validator. You need to handle the validation failure manually. Also your code checks for unique email in the table customers except for the email of the user $request->id. I assume this is intended.
$validator = \Validator::make($request->all(), [
'email' => 'email|unique:customers,email,' . $request->id
]);
if ($validator->fails()) {
// Handle failure
}
The code below will automatically handle validation failure and redirect back with errors and inputs.
$this->validate($request, [
'email' => 'email|unique:customers,email,' . $request->id
]);
You can try something like
Validator::make($data, [
'email' => [
'required',
Rule::unique('customers')->ignore($customer->id),
],
]);

Laravel 5: How to insert error custom messages array inside validate()

I want to insert my validation custom messages inside the validate function as shown:
public function postLogin(Request $request)
{
$rulesemail=['required'=>'Este campo es requerido.'];
$rulespassword=['min'=>'Debe teclear al menos :min caracteres','required'=>'Favor de teclear su contraseƱa'];
$this->validate($request, [
'email' => 'required|email|max:60', 'password' => 'required|min:6'],$rulespassword
);
But i can't get it to work. Any ideas?
You can't with the default validate() from the ValidatesRequests trait.
However you can override the function in your base controller to change that:
public function validate(Request $request, array $rules, array $messages = array())
{
$validator = $this->getValidationFactory()->make($request->all(), $rules, $messages);
if ($validator->fails())
{
$this->throwValidationException($request, $validator);
}
}
And then simply pass the custom messages as third parameter:
$rulesemail=['required'=>'Este campo es requerido.'];
$messages=['min'=>'Debe teclear al menos :min caracteres','required'=>'Favor de teclear su contraseƱa'];
$this->validate($request, [
'email' => 'required|email|max:60',
'password' => 'required|min:6'
], $messages);
Remember that you can also globally define validation messages in a language file. This file is usually located at resources/lang/xx/validation.php
The validate() method accepts 3 parameters:
Request $request, [$errors], [$messages]
Here's an example of how to customise the error message for a validation condition:
$this->validate(
$request,
[
'first_name'=> 'required',
'last_name'=> 'required',
'email' => 'email',
'date_of_birth' => 'date_format:"Y-m-d"'
],
[
'date_format' => 'DOB'
]
);
PHPStorm provides useful tooltip to instantly see the method options.

Resources