简体   繁体   中英

How to validate input before submitting?

I want to validate input before submitting. But something went wrong, every time submit() run :((

const [value, setValue] = React.useState("");
const [error, setError] = React.useState("");
const validate = () => {
  value.length>5?setError("Some errors"):setError("");
}
const submit = () => {do something...}
...
<input onChange={e => setValue(e.target.value)} />

<Button  onClick={() => {
  validate();
  if(!error.length) submit()
}> Submit </Button>

Because the error variable will only contain the new value in the next render of the component. This is due to the way useState , or rather Hooks in general work.

Instead, you'll have to return whether or not the result is valid in the validate function.

const validate = () => {
  value.length>5?setError("Some errors"):setError("");
  return value.length <= 5;
}

<Button  onClick={() => {
  const isValid = validate();
  if(isValid) submit()
}> Submit </Button>

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