laravel验证回调无效


laravel validation callback not work

我正试图使用回调来简单地检查我的表单输入,官方代码如下:https://laravel.com/docs/5.2/validation

以下是我的功能

public function addthread(Request $request) {

    $input = $request->all();
    $rules = array('title' => 'required|unique:thread|max:255');
    $message = array('title.required' => 'The :attribute field is aaa required.');
    $validator = Validator::make($input, $rules, $message);
    $validator->after(function($validator) {
        if ($this->checkOpt()) {
            $validator->errors()->add('num_opt', 'Something is wrong with this field!');
            echo 'test';        
        }
    });
    if ($validator->fails()) {
        return redirect('addthreadhtml')->withErrors($validator)->withInput();
    }
}
public function checkOpt() {
    return false;
}

刀片tpl:

@if (count($errors) > 0)
<div class="container" stytle="max-width:80%">  
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
</div>  
@endif

num_opt错误永远不会打印出来,知道吗?

checkOpt()返回FALSE,因此代码永远不会进入if语句。

if ($this->checkOpt()) { // this is returning false, right ?? so, its not adding the error
        $validator->errors()->add('num_opt', 'Something is wrong with this field!');
        echo 'test';        
    }

您的checkOpt()总是返回false,因此您的条件永远不会得到满足。