简体   繁体   English

反应验证表单,但提交时没有刷新

[英]React validate form but no refresh on submit

I've getting a problem in form submission using React.我在使用 React 提交表单时遇到问题。 I need to:我需要:

  1. use React;使用反应;
  2. validate 'required fields' before submission;在提交之前验证“必填字段”;
  3. prevent page refresh;防止页面刷新;

My DOM looks like the following:我的 DOM 如下所示:

<div>
  <form onSubmit={handleSubmit}>
  <input id='1' type="text" required/>
  <input id='2' type="text" required/>
  <input id='3' type="text" required/>
  <input id='4' type="text" required/>
  <input id='5' type="text" required/>
  <input id='6' type="text" required/>
  ........
  <input id='n' type="text" required/>
  </form>
</div>

and I get my handleSubmit function like the following我得到了我的句柄提交 function 如下

const handleSubmit = (e) => {
  //e.preventDefault    [HERE IS THE ISSUE]
  //something here
}

and now the problem occurs:现在问题出现了:

If I use e.preventDefault() , then nothing is validated onSubmit, they user can leave some field empty and just submit;如果我使用e.preventDefault() ,那么在提交时不会验证任何内容,他们用户可以将某些字段留空并提交; If I comment e.preventDefault() , then the page will refresh when clicking submit, which is wrong.如果我评论e.preventDefault() ,那么点击提交时页面会刷新,这是错误的。

I would like to know, if there is some more detailed method than e.preventDefault(), such as e.preventRefrsh() to prevent the exact step (refresh), and keep those correct steps (validate no empty) as they are.我想知道,是否有比 e.preventDefault() 更详细的方法,例如 e.preventRefrsh() 来阻止确切的步骤(刷新),并保持这些正确的步骤(验证不为空)原样。

Thanks and kind regards, Anson谢谢和亲切的问候,安森

I asked the question above because I was not familiar with the form validation tools of React, and the reason I wanted to use the automatic validation feature, was because whenever a required part is not valid, there should be a small pop-up box telling the user that this part should be filled.我问上面的问题是因为我不熟悉 React 的表单验证工具,而我想使用自动验证功能的原因是因为每当需要的部分无效时,应该有一个小弹出框告诉用户认为这部分应该填写。

I just find two functions reportvalidity that will validate the field and give the popup function, and makes use of the attributes such as required and minlength .我只找到了两个函数reportvalidity来验证字段并给出弹出窗口 function,并利用requiredminlength等属性。 Thanks god, I don't have to write my own validate function, and especially not writing my own popup (as the style must be exactly consistent with other forms on the website, if I do).感谢上帝,我不必编写自己的验证 function,尤其是不必编写自己的弹出窗口(因为样式必须与网站上的其他 forms 完全一致,如果我这样做的话)。

I've also found checkvalidity , but haven't done test on that.我也找到了checkvalidity ,但尚未对此进行测试。 Will update if I do.如果我这样做会更新。

Thanks谢谢

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM