Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: Validator to validate only fields which exist in the passed data?

Currently the Validator will fail if I have a required rule for a key "name", but I haven't passed it in the data array. I want it not to fail in this case. I want to validate only the fields which exist in the data array. Is there a builtin way for that to happen, or I have to extend the Validator class?

like image 321
barakuda28 Avatar asked Jan 12 '14 01:01

barakuda28


People also ask

What is bail in laravel validation?

The bail validation rule applies to a "multi-rule" attribute. It does not stop running validation for other attributes. From the documentation: $request->validate([ 'title' => 'bail|required|unique:posts|max:255', 'body' => 'required', ]);

Is unique validation in laravel?

Laravel includes a wide variety of convenient validation rules that you may apply to data, even providing the ability to validate if values are unique in a given database table.

How do you validate exact words in laravel?

To get the exact words to validate you can make use of Rule::in method available with laravel. Using Rule::in method whatever the values provided by this rule has to be matched otherwise it will fail.


2 Answers

You can use the sometimes validation rule.

In some situations, you may wish to run validation checks against a field only if that field is present in the input array. To quickly accomplish this, add the sometimes rule to your rule list.

http://laravel.com/docs/validation#conditionally-adding-rules

$v = Validator::make($data, array(
    'email' => 'sometimes|required|email',
));

Be sure to run composer update since the sometimes shortcut is a Laravel 4.1.14 feature.

https://twitter.com/laravelphp/status/422463139293057024

like image 145
Holger Weis Avatar answered Sep 30 '22 17:09

Holger Weis


You can use nullable and it will pass if email is not present

$request->validate([
    'name' => 'required',
    'email' => 'nullable|email'
])

Also, you should remove required validation.

like image 38
Eduardo Aguad Avatar answered Sep 30 '22 17:09

Eduardo Aguad