简体   繁体   中英

React validate form but no refresh on submit

I've getting a problem in form submission using React. I need to:

  1. use React;
  2. validate 'required fields' before submission;
  3. prevent page refresh;

My DOM looks like the following:

<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

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; If I comment e.preventDefault() , then the page will refresh when clicking submit, which is wrong.

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.

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.

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 . 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).

I've also found checkvalidity , but haven't done test on that. Will update if I do.

Thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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