使用 React.js 和 Ajax 在 Laravel 5 中显示验证错误

IT技术 ajax laravel-5 reactjs laravel-validation
2021-05-13 13:34:04

我正在运行一个 Laravel 5 应用程序,它的主视图使用 React.js 呈现。在页面上,我有一个简单的输入表单,我正在使用 Ajax 处理它(在没有页面刷新的情况下发回输入)。我验证了 UserController 中的输入数据。我想做的是在我的视图中显示错误消息(如果输入未通过验证)。

我还希望根据 React.js 代码中的状态(已提交或未提交)显示验证错误。

我将如何使用 React.js 而没有页面刷新来做到这一点?

这是一些代码:

React.js 代码:

var ReactCSSTransitionGroup = React.addons.CSSTransitionGroup;

var SignupForm = React.createClass({
  getInitialState: function() {
    return {email: '', submitted: false, error: false};
  },

  _updateInputValue(e) {
    this.setState({email: e.target.value});
  },

  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="button-row">
                                          <a href="#" className="button" onClick={this.saveAndContinue}>Request Invite</a>
                                      </div> 
                                  </ReactCSSTransitionGroup>
                              </div>                            
}
      </div>
    )
  },

  saveAndContinue: function(e) {
    e.preventDefault()

    if(this.state.submitted==false) {
        email = this.refs.email.getDOMNode().value
        this.setState({email: email})
        this.setState({submitted: !this.state.submitted});

        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);},
              success:function(data){},  
        });


        setTimeout(function(){
             this.setState({submitted:false});
        }.bind(this),5000);

    }

  }
});

React.render(<SignupForm/>, document.getElementById('content'));

用户控制器:

public function store(Request $request) {

    $this->validate($request, [
        'email' => 'Required|Email|Min:2|Max:80'
    ]);

    $email = $request->input('email');;

        $user = new User;
        $user->email = $email;
        $user->save();

    return $email;

}

谢谢您的帮助!

1个回答

根据 Laravel 文档,他们在验证失败时发送带有 422 代码的响应:

如果传入请求是 AJAX 请求,则不会生成重定向。相反,带有 422 状态代码的 HTTP 响应将返回给浏览器,其中包含验证错误的 JSON 表示

因此,您只需要处理响应,如果验证失败,则向状态添加验证消息,类似于以下代码片段:

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