Laravel Validation Rule 'same' Negation Check - php

I am trying to write a simple validation rule in laravel framework.
$rules = array(
'from_account' => 'required',
'to_account' => 'required|same:from_account',
'amount' => 'required|numeric',
'description' => 'required'
);
Now as you can see the validation rule same:from_account will check and must require to be to_account exactly same as from_account I am looking to validate for exactly opposite, so that, to_account can't be same as from_account.
Is there any way to tell this negation check inside the rule or do I have to check it manually?

Why not check the docs here.
And use this:
'to_account' => 'required|different:from_account',
or even (for funzies):
'from_account' => 'required|different:to_account',
'to_account' => 'required|different:from_account',

Use the different rule:
$rules = array(
'from_account' => 'required',
'to_account' => 'required|different:from_account',
);

Related

Laravel validate array and exclude on specific array value

I have an array of values that I send together with other fields in a form to laravel.
The array contains a role_id field and a status field, the status can be I (Insert) U (update) D (Delete). When I validate the values in the array I want it to skip the ones where the status equals D. Otherwise I want it to validate.
private function checkValuesUpdate($userid = null)
{
return Request::validate(
[
'displayname' => 'required',
'username' => 'required',
'email' => ['nullable', 'unique:contacts,email' . (is_null($userid ) ? '' : (',' . $userid ))],
'roles.*.role_id' => ['exclude_if:roles.*.status,D', 'required']
]
);
}
I can't seem to get it to work. I've been searching all over the place for functional code as well as the Laravel documentation. But no luck so far. Has anybody ever done this?
Your problem comes from a misunderstanding of the exclude_if rule. It doesn't exclude the value from validation, it only excludes the value from the returned data. So it would not be included if you ran request()->validated() to get the validated input values.
According to the documentation, you can use validation rules with array/star notation so using the required_unless rule might be a better approach. (Note there's also more concise code to replace the old unique rule, and I've added a rule to check contents of the role status.)
$rules = [
'displayname' => 'required',
'username' => 'required',
'email' => [
'nullable',
Rule::unique("contacts")->ignore($userid ?? 0)
],
'roles' => 'array',
'roles.*.status' => 'in:I,U,D',
'roles.*.role_id' => ['required_unless:roles.*.status,D']
];

Laravel validation rules - optional, but validated if present

I'm trying to create a user update validation through form, where I pass, for example 'password'=>NULL, or 'password'=>'newone';
I'm trying to make it validate ONLY if it's passed as not null, and nothing, not even 'sometimes' works :/
I'm trying to validate as :
Validator::make(
['test' => null],
['test' => 'sometimes|required|min:6']
)->validate();
But it fails to validate.
Perhaps you were looking for 'nullable'?
'test'=> 'nullable|min:6'
Though the question is a bit old, this is how you should do it. You dont need to struggle so hard, with so much code, on something this simple.
You need to have both nullable and sometimes on the validation rule, like:
$this->validate($request, [
'username' => 'required|unique:login',
'password' => 'sometimes|nullable|between:8,20'
]);
The above will validate only if the field has some value, and ignore if there is none, or if it passes null. This works well.
Do not pass 'required' on validator
Validate like below
$this->validate($request, [
'username' => 'required|unique:login',
'password' => 'between:8,20'
]);
The above validator will accept password only if they are present but should be between 8 and 20
This is what I did in my use case
case 'update':
$rules = [
'protocol_id' => 'required',
'name' => 'required|max:30|unique:tenant.trackers'.',name,' . $id,
'ip'=>'required',
'imei' => 'max:30|unique:tenant.trackers'.',imei,' . $id,
'simcard_no' => 'between:8,15|unique:tenant.trackers'.',simcard_no,' . $id,
'data_retention_period'=>'required|integer'
];
break;
Here the tracker may or may not have sim card number , if present it will be 8 to 15 characters wrong
Update
if you still want to pass hardcoded 'NULL' value then add the
following in validator
$str='NULL';
$rules = [
password => 'required|not_in:'.$str,
];
I think you are looking for filled.
https://laravel.com/docs/5.4/validation#rule-filled
The relevant validation rules are:
required
sometimes
nullable
All have their uses and they can be checked here:
https://laravel.com/docs/5.8/validation#rule-required
if you want validation to always apply
https://laravel.com/docs/5.8/validation#conditionally-adding-rules
if you want to apply validation rules sometimes
https://laravel.com/docs/5.8/validation#a-note-on-optional-fields
if you want your attribute to allow for null as value too

Laravel 4.2 validation: required_unless

Recently I have been learning Laravel and came accross validator problem that would be solved by using validator rule required_unless from Laravel 5.2:
$validator = Validator::make(
array(
'social_id' => $social_id,
'login_by' => $login_by
), array(
'social_id' => 'required_unless:login_by,manual',
'login_by' => "in:manual,google,facebook, stack_exchange, myspace"
)
);
Problem is that I use Laravel 4.2 and this validation rule is not implemented jet.
Is there any other validating rule I could use or any other way?
If not, how would I write a custom validation rule and where would I put it?
Edit: I could do:
$validator = Validator::make(
array(
'social_id' => $social_id,
'login_by' => $login_by
), array(
'social_id' => 'required_if:login_by,google,facebook, stack_exchange, myspace',
'login_by' => "in:manual,google,facebook, stack_exchange, myspace"
)
);
...but this is just a workaround not an elegant permanent solution.
You can simply extend the Validator with the extend method.
Something like this
Validator::extend('required_unless', function ($attribute, $value, $parameters) {
// Implement your version of required_unless here
});
And even steal a bit of logic from L5.2 here
You can see the doc on extend here

Laravel Validation of email and regex not working

Problem
I am trying to validate a form using the Laravel built in validation. I want to make sure that the email only has a .edu in it. However, there Laravel continues to throw a preg_match(): No ending delimiter '/' found error. I heard this has something to do with a pipe delimiter instead of an array one, but I am unsure what this mean / how to fix it. The code I have is below.
$validator = Validator::make(Input::all(),
array(
'email' => 'Required|Max:50|Email|Unique:users|Regex:/(\.edu(\.[a-z]+)?|\.ac\.[a-z]+)$/',
'first-name' => 'required|max:20|min:3|',
'last-name' => 'required|max:30|min:3|',
'username' => 'required|max:30|min:3|unique:users|',
'city' => '',
'state' => '',
'password-init' => 'required|min:6|AlphaNum',
'password-check', 'required|min:6|AlphaNum|same:password-init'
)
);
Any help would be appreciated
Thanks!
Since you're using pipes | to separate your different validation rules, Laravel gets confused when it sees a pipe in the middle of your Regex. So break up just the "email" rule like this:
$validator = Validator::make(Input::all(),
array(
'email' => array(
'required',
'max:50',
'email',
'unique:users',
'regex:/(\.edu(\.[a-z]+)?|\.ac\.[a-z]+)$/'
),
'first-name' => 'required|max:20|min:3|',
...
That's what it means when it talks about an array instead of pipes in the doc:
http://laravel.com/docs/4.2/validation#rule-regex

CakePHP empty field versus not empty field validations

I have the follow validation rule for a file:
modelFile.php
public $validate = array(
'image' => array(
'maxWidth' => array(
'rule' => array('maxWidth', 2000),
),
'maxHeight' => array(
'rule' => array('maxHeight', 2000),
),
'extension' => array(
'rule' => array('extension', array('gif', 'jpg', 'png', 'jpeg')),
),
'filesize' => array(
'rule' => array('filesize', 5120000),
)
)
);
Have a way to skip validations, if image are empty?
You may have to adjust how you check if the image is empty/not uploaded - I'm not sure if what I have is correct. But the idea is to check and unset the validation rule.
public function beforeValidate($options = array()) {
if (empty($this->data[$this->alias]['image']['name'])) {
unset($this->validate['image']);
}
return true;
}
See below URL
cakePHP optional validation for file upload
Or try it
"I assign $this->data['Catalog']['image'] = $this->data['Catalog']['imageupload']['name'];"
So by the time you save your data array, it looks something like this I assume:
array(
'image' => 'foobar',
'imageupload' => array(
'name' => 'foobar',
'size' => 1234567,
'error' => 0,
...
)
)
Which means, the imageupload validation rule is trying to work on this data:
array(
'name' => 'foobar',
'size' => 1234567,
'error' => 0,
...
)
I.e. the value it's trying to validate is an array of stuff, not just a string. And that is unlikely to pass the specified validation rule. It's also probably never "empty".
Either you create a custom validation rule that can handle this array, or you need to do some more processing in the controller before you try to validate it
Ok, as far as I know there is no such code to set this in your $validate variable. So what you are going to have to do is:
In the beforeValidate of the corresponding model add the following piece of code:
<?php
# Check if the image is set. If not, unbind the validation rule
# Please note the answer of Abid Hussain below. He says the ['image'] will probably
# never be empty. So perhaps you should make use of a different way to check the variable
if (empty($this->data[$this->alias]['image'])){
unset($this->validate['image']);
}
I used http://bakery.cakephp.org/articles/kiger/2008/12/29/simple-way-to-unbind-validation-set-remaining-rules-to-required as my main article. But this function doesn't seem to be a default cake variable. The code above should work.

Categories