Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.4 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.

like image 331
GTMeteor Avatar asked Feb 18 '17 18:02

GTMeteor


3 Answers

Perhaps you were looking for 'nullable'?

'test'=> 'nullable|min:6'
like image 191
Matt K Avatar answered Oct 18 '22 11:10

Matt K


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.

like image 8
nixxx Avatar answered Oct 18 '22 09:10

nixxx


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,
];
like image 3
sumit Avatar answered Oct 18 '22 09:10

sumit