首页 > 其他 > 详细

Prevent form submit before pass the validation with React-Rails

时间:2017-09-06 12:17:18      阅读:270      评论:0      收藏:0      [点我收藏+]

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!