0

Faced the problem while using Laravel 4 validation. Here's the code:

$validator = Validator::make(
              array(
                  'surname' => ['Laravel'],
              ),
              array(
                  'surname' => 'integer|alpha_dash'
              )
        );
        $validator->passes();        
        var_dump($validator->failed());

It causes error: Error: preg_match() expects parameter 2 to be string, array given

Lets suppose surname comes from user and it can be array or string.

I have two questions:

  1. Why alpha_dash causes error instead of normal validation error?
  2. Why validation continues to 'alpha_dash' rule after we got FALSE on 'integer' rule? Is this a bug?

1 Answer 1

2

What I just did to test arrays:

Created some fields the way you are doing:

<input type="text" name="user[surname][0]">
<input type="text" name="user[surname][1]">

And validated one of them:

$validator = \Validator::make(
    Input::all(),
    array('user.surname.0' => 'required|min:5')
);

var_dump($validator->passes());

Then I just did it manually:

$validator = \Validator::make(
    array(
        'user' => ['surname' => [ 0 => 'Laravel'] ],
    ),
    array('user.surname.0' => 'required|min:5')
);

And it worked on both for me.

If you need to analyse something Laravel doesn't provide, you can extend the Validator by doing:

Validator::extend('foo', function($attribute, $value, $parameters)
{
    return $value == 'foo';
});

EDIT

But, yeah, there is a bug on it, if you do:

$validator = \Validator::make(
    array(
        'user' => ['surname' => [ 0 => 'Laravel'] ],
    ),
    array('user.surname.0' => 'integer|alpha_dash')
);

It will give you a

"Error: preg_match() expects parameter 2 to be string, array given".

Here's the Laravel issue posted by the OP: https://github.com/laravel/laravel/issues/2457.

Sign up to request clarification or add additional context in comments.

9 Comments

I know that's an array. I'm asking why i have error instead of standart validation message? What if user posts an array?
Because you are supposed to send the correct data to be processed by the validator, validator is expecting a string there, not an array.
print_r(\Input::all()); Array ( [surname] => Array ( [0] => Laravel ) )
That's odd. Could you share your view?
Here's an example of get query: ?user[surname][0]=Laravel
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.