问题
I am running a Laravel 5 application that has its main view rendered using React.js. On the page, I have a simple input form, that I am handling with Ajax (sending the input back without page refresh). I validate the input data in my UserController. What I would like to do is display error messages (if the input does not pass validation) in my view.
I would also like the validation errors to appear based on state (submitted or not submitted) within the React.js code.
How would I do this using React.js and without page refresh?
Here is some 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!
回答1:
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)
});
After that, in the 'render' method, just check if this.state.validationErrorMessage is set and render the message 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>
)
}
来源:https://stackoverflow.com/questions/31487641/displaying-validation-errors-in-laravel-5-with-react-js-and-ajax