Display validation errors in Laravel 5 using React.js and Ajax

I am launching a Laravel 5 application that has a basic look displayed with React.js. On the page, I have a simple input form that I process with Ajax (sending input back without refreshing the page). I am checking the input in my UserController. What I would like to do is to display error messages (if the input fails verification) in my opinion.

I would also like verification errors to be displayed based on status (sent or not sent) in React.js code.

How can I do this with React.js and without refreshing the page?

Here is the code:

React.js Code:

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

UserController:

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

Thank you for your help!

+6
source share
1 answer

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

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

So, you just need to process the response, and if the verification fails, add the verification message to the state, something like the following code fragment:

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

After that, in the "render" method, simply check if this.state.validationErrorMessage is set and a message is displayed somewhere:

  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> ) } 
+9
source

All Articles