【问题标题】:Can I validate form input also without using the laravelcollective/html namespace in a Laravel application?我可以在 Laravel 应用程序中不使用 laravelcollective/html 命名空间的情况下验证表单输入吗?
【发布时间】:2017-07-11 03:45:37
【问题描述】:

我是 PHPLaravel 框架的新手,我有以下疑问。

我正在按照本教程将 reCAPTCHA 插入表单(但我的疑问更多的是与表单验证相关而不是 reCAPTCHA):http://tutsnare.com/how-to-use-captcha-in-laravel-5/

所以要声明一个表单,它在视图中使用以下语法:

{!! Form::open(array('url'=>'contact','method'=>'POST', 'id'=>'myform')) !!}

我认为这个语法与 laravelcollective/html 命名空间有关,是吗?

所以我安装了它来执行语句:

composer require "laravelcollective/html":"^5.4"

在控制器方法中定义了这个index()方法来处理表单sumbit操作:

<?php namespace App\Http\Controllers;
use Input;
use Validator;
use Redirect;
use Session;
class EnquiryController extends Controller {
    public function index()
    {
        $data = Input::all();
        $rules = array(
            'name' => 'required',
            'email' => 'required|email',
            'subject' => 'required',
            'g-recaptcha-response' => 'required|captcha',
            'msg' => 'required',
        );
        $validator = Validator::make($data, $rules);
        if ($validator->fails()){
            return Redirect::to('/contact')->withInput()->withErrors($validator);
        }
        else{
            // Do your stuff.
        }
    }
}

所以,正如您在前面的代码 sn-p 中看到的,此方法使用 $rules 数组提供输入验证,如果验证失败,则会重定向到显示包含验证的同一页面错误:

return Redirect::to('/contact')->withInput()->withErrors($validator);

这部分代码将在视图中打印:

@if (count($errors) > 0)
    <div class="alert alert-danger">
        <strong>Whoops!</strong> There were some problems with your input.<br /><br />
        <ul>
            @foreach ($errors->all() as $error)
               <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

我的疑问是:我是否可以使用纯 HTML 表单而不是 laravelcollective/html 命名空间提供的表单,以同样的方式验证表单输入并返回潜在错误?

【问题讨论】:

    标签: php laravel laravel-5 laravel-validation laravelcollective


    【解决方案1】:

    是的,如果需要,还可以做更多的验证逻辑。

    您可以对表单请求https://laravel.com/docs/5.4/validation#form-request-validation 和其他一些验证采取方法。

    此外,after 钩子允许在规则定义发生之前进行评估。

    /**
     * Configure the validator instance.
     *
     * @param  \Illuminate\Validation\Validator  $validator
     * @return void
     */
    public function withValidator($validator)
    {
        $validator->after(function ($validator) {
            if ($this->somethingElseIsInvalid()) {
                $validator->errors()->add('field', 'Something is wrong with this field!');
            }
        });
    }
    

    【讨论】:

      【解决方案2】:

      是的,您可以使用普通的 html 进行验证。

      "laravelcollective/html": "~5.0" 
      

      这里是安装过程:https://laravelcollective.com/docs/5.0/html

      这里是验证说明:https://laravel.com/docs/5.0/validation#basic-usage

      谢谢

      【讨论】:

        猜你喜欢
        • 2023-03-16
        • 2021-03-23
        • 1970-01-01
        • 1970-01-01
        • 2010-11-04
        • 2011-12-16
        • 2013-04-03
        • 2013-06-13
        • 2017-05-01
        相关资源
        最近更新 更多