如何在Laravel刀片中的React组件中获取Laravel验证错误

时间:2019-11-30 07:50:28

标签: javascript html reactjs laravel laravel-blade

我是React的新手。我在Laravel刀片中使用部分的react form组件。然后如何将验证错误消息从控制器发送到驻留在Laravel刀片文件中的React组件。

在我的控制器中,

Data Structure and Algorithm

在我的laravel刀片中,

public function store(Request $request)
{
    $rules = [
      'name' => 'required',
      'publish_at' => 'required|datetime'
    ];

    $this->validate($request, $rules);

    $book = Book::create([
        'name' => $request->name,
        'publish_at' => $request->publish_at
    ]);

    return response()->json($book);
}

1 个答案:

答案 0 :(得分:0)

  

根据Laravel文档,他们使用422代码发送响应   验证失败:

     

如果传入请求是AJAX请求,则不会重定向   产生。取而代之的是,HTTP响应带有422状态代码   返回到包含JSON表示形式的浏览器   验证错误

*So, you just need to handle response and, if validation failed, add a
validation message to the state, something like in the following code
snippet*


  request = $.ajax({ 
              url: "/user", 
              type: "post", 
              data: 'email=' + email + '&_token={{ csrf_token() }}',
              data: {'email': email, '_token': $('meta[name=_token]').attr('content')},
              beforeSend: function(data){console.log(data);},
              error: function(jqXhr, json, errorThrown) {
                if(jqXhr.status === 422) {
                    //status means that this is a validation error, now we need to get messages from JSON
                    var errors = jqXhr.responseJSON;
                    var theMessageFromRequest = errors['email'].join('. ');
                    this.setState({
                        validationErrorMessage: theMessageFromRequest,
                        submitted: false
                    });
                }
              }.bind(this)
        });

然后,在“ render”方法中,只需检查是否设置了this.state.validationErrorMessage并将消息呈现在某处:

render: function() {
    var text = this.state.submitted ? 'Thank you!  Expect a follow up at '+email+' soon!' : 'Enter your email to request early access:';
    var style = this.state.submitted ? {"backgroundColor": "rgba(26, 188, 156, 0.4)"} : {};
    return (
      <div>
        {this.state.submitted ? null :
            <div className="overall-input">
              <ReactCSSTransitionGroup transitionName="example" transitionAppear={true}>
                  <input type="email" className="input_field" onChange={this._updateInputValue} ref="email" value={this.state.email} />
                  <div className="validation-message">{this.state.validationErrorMessage}</div>
                  <div className="button-row">
                      <a href="#" className="button" onClick={this.saveAndContinue}>Request Invite</a>
                  </div> 
              </ReactCSSTransitionGroup>
            </div>                            
        }
      </div>
    )
  }