prospero's avatar

Validation using Closures

Hi guys. As the title said, I'm doing validation using closure in specific thing. In multiform when validate the entries if some field validation fail I can switch tabs in each case. This couldn't be the best way but is working for me. For example is I validate for a required text field and it's leng I do:

if($this->validate([
     'name' => [function($attribute, $value, $fail) {
             if (empty($value)) {
                  $this->tab = 'basic';
             }
             elseif(strlen($value) < 2) {
                  $this->tab = 'basic';
             }
       //........

This return to the proper tab and showing the error bag. But now, I need to validate an upload field for "logo" property, which must be validated like 'image', 'max:1024', 'dimensions:min_width=500,min_height=500' validation rules. How, I can check $value for this using this logic or if you get some custom solution? Hope you understand well and kick this ! ;)

0 likes
4 replies
gitwithravish's avatar

Well there could be many simple approaches for that. But if you want to go with only this sort of design, then create a validator object inside the closure. Validate using the existing rules and take action based on validation failure/success.

Again, this is a bad practice, but if you want to just do it this way then you can do it like that.

prospero's avatar

If you can share other simplest way to do this, and get the same result I'm open to rewrite my code and would very glad for that, I'm always ready for learn.

gitwithravish's avatar
Level 16

If you have 3 tabs, then make 3 validators

// create validator for 1st tab
$validator = Validator::make($request->all(), [
	'field_1' => 'rules...',
	'field_2' => 'rules...'
	...
]);

// check if tab 1 fails
if($validator->fails()){
	// return error with tab name
}

// create validator for 2nd tab
$validator = Validator::make($request->all(), $tab2Rules);


// check if tab 1 fails
if($validator->fails()){
	// return error with tab name
}

@prospero hope that helps :)

Please or to participate in this conversation.