0

我在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"

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

<?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.
        }
    }
}

因此,正如您在前面的代码片段中所见,此方法使用$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命名空间提供的相同方式验证表单输入并返回潜在错误?

4

2 回答 2

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!');
        }
    });
}
于 2017-02-21T13:42:05.293 回答
1

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

"laravelcollective/html": "~5.0" 

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

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

谢谢

于 2017-02-21T13:34:39.843 回答