laravel 5.4带键的验证数组

时间:2017-04-13 12:46:00

标签: validation laravel-5

在laravel 5.4中,当验证失败时,我喜欢:

if ($validator->fails()) {
                $errors_list = $validator->messages()->all();

我得到的数组如下:

[errors_list] => Array
    (
        [0] => The image has already been taken.
        [1] => The is main has already been taken.
    )

我不喜欢在此输出中省略了错误字段的名称。

代码

echo '<pre>$validator->messages()::'.print_r($validator->messages(),true).'</pre>';

有输出:

$validator->messages()::Illuminate\Support\MessageBag Object
(
    [messages:protected] => Array
        (
            [image] => Array
                (
                    [0] => The image has already been taken.
                )

            [is_main] => Array
                (
                    [0] => The is main has already been taken.
                )

        )

    [format:protected] => :message
)

我没有找到如何访问消息数据。

我想得到如下数组:

[errors_list] => Array
        (
            [image] => The image has already been taken.
            [is_main] => The is main has already been taken.
        )

有办法吗?

谢谢!

2 个答案:

答案 0 :(得分:1)

我希望这对你有用。

$errors->has('image');
$errors->get(image);

$errors->has('is_main');
$errors->get(is_main);

答案 1 :(得分:0)

这是一个棘手的问题。它之所以如此,是因为可能会同时发生多个验证错误。但是,如果每个条目只有一个规则:

@Override
public boolean onPreferenceChange(Preference preference, Object obj) {
    if (!(preference instanceof EditTextPreference && obj instanceof String)) {
        return false;
    }

    EditTextPreference editTextPreference = (EditTextPreference)preference;
    String key = editTextPreference.getKey();
    String oldValue = editTextPreference.getText();
    String newValue = String.valueOf(obj);

    Log.d(TAG, String.format("key %s, value %s -> %s", key, oldValue, newValue));

    // TODO validate the newValue and return true or false