码迷,mamicode.com
首页 > 其他好文 > 详细

Prevent form submit before pass the validation with React-Rails

时间:2017-09-06 12:51:14      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:pos   sub   first   following   rails   failed   end   ble   not   

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

标签:pos   sub   first   following   rails   failed   end   ble   not   

原文地址:http://www.cnblogs.com/ivyfu/p/7483994.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!