How to add the parameter name in custom validation laravel - php

I want to ask about custom validation. I make validation for counting the word
Validator::extend('word_count', function($attribute, $value, $parameters, $validator) {
return str_word_count($value) >= $parameters;
});
How can i give name to parameter so that i can use the parameter value in error message?

Based on your question, i will understand you care about the validation message.
If you are looking for validation message mean, you can use custom message like,
If you are using the request file means, there we can use
messages(){
return [
'word_count' => '....', //some message will be here,
];
}
If you are using controller means, then use like
return response()->json('...', 422);
or
here also you can use that above messages function.
I hope, it will help you.If any thing ask here.

Related

Lumen Validation allow only one Get Parameter

In my project I use Lumen and I want to implement some kind of validation for my GET request.
The example URL would look like this:
[URL]/blubb/bla?tags[]=1&tags[]=2
In my code I validate the URL like this:
public function handleRequest(Request $request)
{
try {
$validatedData = $this->validate($request, [
'tags' => 'nullable|array'
]);
} catch (ValidationException $th) {
// return Error.
}
// go on.
}
My problem is that if a user uses an URL like this one, the validation does not trigger and the "go on." part is called.
[URL]/blubb/bla?invalidParameter=1
Is there a way to only allow a single "kind" of GET Parameter?
EDIT:
The "tags" is nullable because my API endpoint can be called without any GET parameters.
You could get the full array with $request->all() and have a look at the keys.
$paramValidation = $request->all()
unset $paramValidation['tags'];
if (count($paramValidation)) {
// error
}
However, maybe you just want to ignore other params. Have a look at the method $request->validated().

Can't add custom rule when using the vlucas/valitron form validation package

I've been trying to add a custom rule to the Valitron validator, but without success. The documentation is here
My own custom rule didn't work, so I tried using the simplest possible implementation with the actual example from the documentation, and the rule still doesn't trigger. Here is what I have:
$input = [
'building'=>'',
'other_building'=>''
];
Valitron\Validator::addRule('alwaysFail', function($field, $value, array $params, array $fields) {
return false;
}, 'Everything you do is wrong. You fail.');
$v = new Valitron\Validator($input);
$v->rule('required', ['building']);
$v->rule('alwaysFail', 'other_building');
When I call $v->errors() it returns the 'Building required' error, but not the error message for 'alwaysFail.' I've also tried the format for just adding a custom rule for a specific field:
$v = new Valitron\Validator($input);
$v->rule(function($field, $value, $params, $fields) {
return false;
}, "other_building")->message("{field} failed...");
If I dump out the value of $v I can see that the rule is in there, attached to other_building. But it never fails validation (I've also tried having the rule return true just to see what happens - same result). Please help! Thank you.
Okay, I figured it out. It seems a bit obvious in retrospect, but I've been working on this for a couple of days. The problem is that 'other_building' is blank, and is allowed to be blank (e.g. not required). Therefore the validator is passing over it and never checking the rule. If you put in a non-blank value for 'other_building', it works. It also works if you leave it blank, but add a rule that 'other_building' is required. If you don't want the field to be required, but you also want the rule to run every time 'other_building' is in the data, even if the value is blank, you need to add an 'optional' rule, which states that "Value does not need to be included in data array. If it is however, it must pass validation."
So this works:
$input = [
'building'=>'',
'other_building'=>''
];
$v = new Valitron\Validator($input);
$v->rule('optional', ['other_building']);
$v->rule(function($field, $value, $params, $fields) {
return false;
}, "other_building")->message("{field} failed...");
I guess this problem was too niche to attract any commentators, but I'll leave it up in case it helps someone else in the future.

Laravel validate regex - Email inside text

I need to check the presence of any email within a text in a textarea.
If there's any email present the form should fail.
I did regex to fail if there is no email present regex:/[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}/ and it should be easy to do the negation but I'm not having any success.
Add this code into AppServiceProvider boot method:
Validator::extend('not_regex', function($attribute, $value, $parameters, $validator) {
if (!is_string($value) && !is_numeric($value)) {
return false;
}
return !preg_match($parameters[0], $value);
});
And then just use your regex like this:
not_regex:"/[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}/"
I think the best way to solve this is to create your own custom validation rule. This way you can solve this problem using nicely formatted code.
Laravel comes with an "email" validation rule which is very easy to implement. You can read all about it, and other validation methods in this link.

Is there a validation rule for "not present"?

I need to check if the key is not set in the array using Laravel validator.
That would be the complete opposite of the "required" validation rule.
Basically the array will be passed to update method if it passes the validation and I want to make sure one column will not be updated.
Is there a way to check if the value "is not present"?
Thank you
EDIT:
I'm currently using Laravel 5
EDIT:
I managed to write my own validation rule by calling Validator::extendImplicit. However I get $value as null to my validation function both when I set it to null or when I don't set it at all. Is there a way to check if the value is set?
I believe I found a solution:
$validator->extendImplicit('not_present', function($attribute, $value, $parameters)
{
return !array_key_exists($attribute, $this->data);
});
I'm not calling extendImplicit statically because the Validator class object is injected to the controller of my class.
I need to access $this->data ($this referring to the Validator object) to make sure the key doesn't exist in the array being validated.
Based on the #MaGnetas answer I came up with this 2 rules that can be applied on any model.
I'm using Laravel 5.4 so putting this lines on your AppServiceProvider.php should work.
The first approach (extendImplicit and array_key_exists)
Validator::extendImplicit('not_present', function($attribute, $value, $parameters, $validator)
{
return !array_key_exists($attribute, $validator->getData());
});
Ussing $validator->getData() we could use the Validator statically.
The second approach (extend and false)
Validator::extend('not_present', function($attribute, $value, $parameters, $validator)
{
return false;
});
You could use extend because we don't need the rule to be executed if the data has not the property (because that's exactly what we want right?)
On the docs:
By default, when an attribute being validated is not present or contains an empty value as defined by the required rule, normal validation rules, including custom extensions, are not run. more info
Important: The only difference is that using extend, empty strings will not run the validation. But if you have setting TrimStrings and ConvertEmptyStringsToNull on your middleware (which AFAIK is the default option) there will be no problem
No there is no build in validtion rule for this, but you can create your own validation rule.
The simplest way to do this:
Validator::extend('foo', function($attribute, $value, $parameters)
{
// Do some stuff
});
And check if key exists.
More information:
http://laravel.com/docs/4.2/validation#custom-validation-rules
For people looking for the not_present logic in 7.x apps (applicable for all versions), remember that you can simply use the validated data array for the same results.
$validatedKeys = $request->validate([
'sort' => 'integer',
'status' => 'in:active,inactive,archived',
]);
// Only update with keys that has been validated.
$model->update(collect($request->all())->only($validatedKeys)->all());
my model has more attributes but only these two should be updatable, therefore I too were looking for an not_present rule but ending up doing this as the results and conceptual logic is the very same. Just from another perspective.
I know this question is really old but you can also use
'email' => 'sometimes|required|not_regex:/^/i',
If the email is present in the request, the regex will match any characters in the request and if the email is an empty string but is present in request the sometimes|required will catch that.

Laravel custom validation issue

I am trying to register a custom validation rule but it does not seem to work. I need either of 2 fields to be filled in. One is a URL(link) field and other is a File input(file_upload).
Here is my custom validation:
Validator::register('file_check', function($attribute, $value, $parameters) {
if (!trim($value) == "" || array_get(Input::file($parameters[0]), 'tmp_name')) {
return true;
}
return false;
});
$messages = array(
'file_check' => 'Please upload a file or provide a link to files.',
);
$rules = array(
'link' => 'url|file_check:file_upload',
'file_upload' => 'mimes:jpg,jpeg,gif,png,psd,ai,bmp,xls,xlsx,doc,docx,zip,rar,7z,txt,pdf'
);
$validation = Validator::make(Input::all(), $rules, $messages);
if ($validation - > fails()) {
return Redirect::to('page') - > with_errors($validation - > errors) - > with_input();
}
Need help :)
EDITED
Also, I just noticed that the validation rule should accept "PSD" files but when I try to upload a PSD file it redirects with the error "Invalid file type".
I am maybe late in party but may be somebody will find it useful, in case you need to create implicit rule which will be called even if field is not present in Input (like required,required_if....) use
Validator::extendImplicit( 'validator_name', function($attribute, $value, $parameters)
{
});
Check this out
I was just struggling with this myself! It turns out that except when a few specific rules are applied to them, Laravel doesn't pass empty fields through the Validator at all. So a custom either-this-or-that rule can't work, since at least one of the two fields is likely to not be visible to it.
You can get around this by moving from the registering-a-new-rule approach to the alternate extend-the-Validator-class approach. Your new class will inherit all the methods of the standard Validator, including a method called "implicit" (you can find the original on line 215 of the standard Validator class), which specifies a whitelist of rules that Laravel should pass fields along to even if they are empty. Add your new rule to that list and you should be good to go.
Jason is right, but there is one thing that can be confusing.
Laravel's 'registering a new rule' approach uses the syntax 'Validator::extend(...'. As described elsewhere, this is convenient when you want to customize in a special situation. However, if you want to add a number of reusable rules, then you probably want to use the extend-the-Validator-class approach. In that case, IF you have a rule conditionally requires something, you need to override the existing implicitRules array with a new one adding your rule.
If the first rules you add don't conditionally require, you will think you have it nailed, then you will spend hours trying to figure out why your new 'RequireWhenBlaBla...' rule is invisible.

Categories