Laravel Validation: bail rule not working - php

According to Laravel Documentation, bail rule should stop running validation rules after first validation failure.
I have a file outside App\Http\* namespace with the following code in it:
if(Validator::make($params, [
'email' => 'bail|required|email|max:60|exists:customers,email',
'password' => 'required|max:60|string',
'password' => new CustomerCheckPassword($params['email']),
]) -> fails())
throw new Exception('message here');
Works like a charm, except bail rule from email attribute does not stop the validation when $params['email'] is not contained by customers.email, and goes on to password as well. Do you have any ideas or elegant workarounds for this issue?

In a different section of the same docs page (it won't link directly to it), it explains that bail only applies to the current attribute. So for instance, if email is missing, it will not check anything after required, but password is a new attribute so it will validate it as normal.
Sometimes you may wish to stop running validation rules on an attribute after the first validation failure. To do so, assign the bail rule to the attribute:
One way to accomplish this would be to use the sometimes method
Validator::make($params, [
'email' => 'bail|required|email|max:60|exists:customers,email',
'password' => 'required|max:60|string',
])->sometimes('password', new CustomerCheckPassword($params['email']), function ($input) {
// Check input to decide if rule should execute
});

Related

Yii 1.1 RegEx match validation is not working

I need to validate that a customer is using a valid subdomain name as well as making sure some other required fields are present. I have created the following rule in my model class:
public function rules()
{
return array(
array(',c_customerSubdomain, c_custAdminUser,c_adminPassword,c_adminContact', 'required', 'message' => "{attribute} is TEST required."),
array('c_customerSubdomain', 'match', 'pattern' => '/^[a-z0-9_]*$/', 'message' => "Customer Subdomain should contain only alphanumeric and underscore.", "allowEmpty" => false),
);
}
I am testing whether or not the rule is firing by changing the message for required values to: {attribute} is TEST required.
When I submit the form with all of the field blank, the result is as expected.
However, when I populate the field for subdomain with an illegal value, such as "ASD# a", I am expecting to get a validation error. However, instead, the rules bypass all of the other validation errors and attempt to save the model.

Laravel Request Validation Regex without Required

I have a problem with Request validation. Everything works but one pattern. And its if I dont want the field to be required but once it is filled I want it to match a regex.
But it throws regex error when I leave the field empty.
Any tips on how I should handle it?
BTW: I made a custom Request class where I take care of the validation so if the solution could be also in the Request and not directly in Controller that would be great.
return [
'dic' => 'max:12|regex:/^[a-zA-Z]{2}[0-9]{8}[0-9]*$/',
];
return [
'dic' => 'nullable|max:12|regex:/^[a-zA-Z]{2}[0-9]{8}[0-9]*$/',
];
nullable won't check the other rules when the field is empty.

Laravel api route validation not validating

I did move from Lumen to Laravel and now converting my project over. Everything is working except the validation. For some reason, if I try to validate, it just redirects to the welcome.blade.php view. What could cause this?
I am using only the API part of routes, not the view. I am not dealing with views. I am using the stateless part of Laravel.
According to documentation, I can validate like this:
$this->validate($request, [
'title' => 'required|unique|max:255',
'body' => 'required',
]);
If validation passes, your code will keep executing normally. However,
if validation fails, an
Illuminate\Contracts\Validation\ValidationException will be thrown.
I also tried to force it to return JSON response without success:
$validator = $this->validate($request, ['email' => 'required']);
if ($validator->fails()) {
$messages = $validator->errors();
return new JsonResponse(['status' => 'error', 'messages' => $messages]);
}
However, mine doesn't fail but just returns the welcome view with response code of 200. I have tried pretty much all the possible validation methods from the documentation and from google. Non of them are working.
I even tried with clean laravel install, declared one test route and test controller which had the validation and the result is the exact same.
Is the validation even meant to be compatible with the restful/stateless part of Laravel?
Any suggestion is much appreciated.
1- first the unique key needs a table, per example if you want the email to be unique in the users table you do as follows:
'email' => 'required|unique:users',
I think may be you have placed your route in route/web.php file. Replace that code from web.php to api.php
Try to place your API endpoints in route/api.php file.
And remember you need to add prefix /api in your route.
Ex : test.com/api/users.

Laravel: Apply validation rule only if the another one passed

In my Laravel 5.2 app, I have the following validation rules to check a field:
$rules = array(
'file' => 'mimes:jpg,png,pdf,doc,docx',
'file' => 'validate_file'
);
Now, the validate_file is a custom validation rule. I want to run it only only if the first mimes validation passes.
I know I could simply validate/redirect with errors - in two batches, first the mimes, then the validate_file, but it seems like an overkill.
Any way I can do it the smart way in Laravel 5.2?
Use "bail" attribute. It will stop validation after first failure.
$this->validate($request, [
'title' => 'bail|mimes:jpg,png,pdf,doc,docx|validate_file',
]);
https://laravel.com/docs/5.2/validation#validation-quickstart search for "bail"

Laravel 4 field validation issues on edit

I am using a simple user auth package. It has default validation on user creation, however, it does not have any sort of user edit functionality. No problem, I can write that in. The problem I am having is on update of the username I am failing validation for the following:
The email has already been taken.
The password must be between 4 and 11 characters.
The password confirmation does not match.
When editing, the email is taken because it's the same email. I'm not evenn editing the password.
So my question: How do I turn off validation for updating/editing, or better yet, how do I apply different validation rules for those methods?
You can do that by changing default values, which are provided with package. They can be found on line 50:
public static $rules = array(
'username' => 'required|alpha_dash|unique:users',
'email' => 'required|email|unique:users',
'password' => 'required|between:4,11|confirmed',
'password_confirmation' => 'between:4,11',
);
In a class ConfideUser.
Just replace those rules with you own. In case you dont have some rules e.g. password_confirmation, then delete it. And also adopt your HTML forms and models/db with new validatiorn rules.
I hope it helps.

Categories