【问题标题】:Laravel 4 validation constant passLaravel 4 验证常量通过
【发布时间】:2014-10-09 00:35:16
【问题描述】:

我正在使用 Laravel 4.2.8 并尝试验证下一个表单:

第一个选择字段是必需的。接下来的三个字段只需要一个。 带格式的电话是最后一个。另外两个用于数字(某些 ID)。 我在控制器中验证,代码是下一个:

public function getApplication()
{
    $input = Input::except('_token');
    Debugbar::info($input);
    $input['phone'] = preg_replace('/[^0-9]/', '', $input['phone']); // remove format from phone
    $input = array_map('intval', $input); // convert all numeric data to int
    Debugbar::info($input);

    $rules = [ // Validation rules
        ['operation-location' => 'required|numeric'],
        ['app-id' => 'numeric|min:1|required_without_all:card-id,phone'],
        ['card-id' => 'numeric|digits:16|required_without_all:app-id,phone'],
        ['phone' => 'numeric|digits:12|required_without_all:app-id,card-id']
    ];

    $validator = Validator::make($input, $rules);
    if ($validator->passes()) {
        Debugbar::info('Validation OK');

        return Redirect::route('appl.journal', ['by' => 'application']);
    }
    else { // Validation FAIL
        Debugbar::info('Validation error');
        // Redirect to form with error
        return Redirect::route('appl.journal', ['by' => 'application'])
            ->withErrors($validator)
            ->withInput();
    }
}

如您所见,我自己将数字 ID 转换为整数,只留下电话号码的数字。 问题是当我按原样提交表单时,它通过了验证,尽管需要一个字段并且启动电话格式太短。 我已经尝试将 required_without_all 更改为所有字段都需要(!),但它仍然可以通过提交空白的空表单。 而且我希望至少有一个字段被正确填写。

调试我的输入。 首字母:

    array(4) [
    'operation-location' => string (1) "0"
    'app-id' => string (0) ""
    'card-id' => string (0) ""
    'phone' => string (6) "+3 8(0"
]

转换为int后:

    array(4) [
    'operation-location' => integer 0
    'app-id' => integer 0
    'card-id' => integer 0
    'phone' => integer 380
]

将类似的小问题发布到Laravel issues

【问题讨论】:

    标签: php forms validation laravel laravel-4


    【解决方案1】:

    我知道这听起来很奇怪,但我认为这只是您的规则数组的问题。

    您当前的规则数组是一个数组数组。 Validator 会查找包含键和值的数组。我相信您当前的规则被解析为键,但没有任何价值。然后 Validator 基本上看不到任何规则,它自动通过了。试试这个。

    $rules = [
        'operation-location' => 'required|numeric',
        'app-id' => 'numeric|min:1|required_without_all:card-id,phone',
        'card-id' => 'numeric|digits:16|required_without_all:app-id,phone',
        'phone' => 'numeric|digits:12|required_without_all:app-id,card-id'
    ];
    

    【讨论】:

    • 非常感谢!我怎么会错过这个。
    • 没问题,伙计。我们都会时不时犯下这些愚蠢的错误。
    猜你喜欢
    • 2014-10-02
    • 2013-05-07
    • 2014-03-09
    • 1970-01-01
    • 2013-09-09
    • 2015-06-28
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    相关资源
    最近更新 更多