javascript - 如何在 Laravel Blade 中的 React 组件中获取 Laravel 验证错误

标签 javascript html reactjs laravel laravel-blade

我是 React 新手。我在 Laravel Blade 中部分使用 react 表单组件。那么我如何将验证错误消息从 Controller 发送到驻留在 Laravel Blade 文件中的 react 组件。

在我的 Controller 中,

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);
}

在我的 laravel Blade 中,

 <form method="POST" action="patients">
     @csrf
     <div class="form-group">
         <label for="name">Name</label>
         <input type="text" name="name" class="form-control" placeholder=". . .">
         @error('name')
         <span class="text-danger">{{ $message }}</span>
         @enderror
     </div>

     <div id="publish_at"></div> <!-- this is react component -->

     <button type="submit">Submit</button>
</form>

最佳答案

According to Laravel docs, they send a response with 422 code on failed validation:

If the incoming request was an AJAX request, no redirect will be generated. Instead, an HTTP response with a 422 status code will be returned to the browser containing a JSON representation of the validation errors

*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>
    )
  }

关于javascript - 如何在 Laravel Blade 中的 React 组件中获取 Laravel 验证错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59114304/

相关文章:

javascript - 如何通过 jQuery 保持鼠标悬停的 DIV 可见?

javascript - 如何获取 child Prop

javascript - 多个 ID 和类共享 AddEventListener

javascript - 同步 html 中的文本区域

javascript - 如何使用 jquery 在 onChange 中保持多个选择同步

html - 图像旁边的按钮对齐

javascript - 如何查找第三方网页中哪些函数与UI事件绑定(bind)?

javascript - 无法正确更新状态中的总值

javascript - 在 React 中迭代点击

javascript - Leaflet:检索 KML 多边形的边界