I‘ve been working on Rails app refactoring by react-rails recently. We want to use React components but keep the advantages of Rails at the same time. So typically Rails will handle the CRUD and the route.
Now I‘m facing a problem which is how to use rails Login form submit controller but only when the form pass the validation.
I figured it out by the following steps.
Step 1: Add onSubmit event inside the form tag
This form inside Login component will automatically submit base on the action={path} setting. Now we have the onSubmit event setting, will give us a chance to do validation first in front-end.
class Login extends React.Component { render() { const { path } = this.props; return ( <div className="row"> <form className="new_user" action={path} method="POST" onSubmit={(e) => this.handleSubmit(e)} > ...... </form> </div> ) } }
Step 2: Define the handleSubmit() function inside the component
Run e.preventDefault() will stop the auto form submit.
Notice: Beware don‘t do e.preventDefault outside the condition part. Only do it when we confirm the input couldn‘t pass the validation.
... handleSubmit (e) { let validationFailed = this.validation(); if (validationFailed) { e.preventDefault(); return false; } } ...
Step 3: Define the validation() function
Put any validation options here as you need. For example: (Notice when return true means doesn‘t pass the validation)
... validation() { const email = $(‘#user_email‘).val(); const pass = $(‘#user_password‘).val() if (email == "" || pass == "") {
// Add as many as you want to finish the validation here return true; //Fail to pass the validation } return false; //All good, ready to submit } ...
Prevent form submit before pass the validation with React-Rails
原文:http://www.cnblogs.com/ivyfu/p/7483994.html