Home > OS >  how to create a form which will only allow to submit if the input is not empty and is > 0?
how to create a form which will only allow to submit if the input is not empty and is > 0?

Time:12-01

I want to make a logic before submitting which states that input value shouldn't be any empty value and it should be greater than 0.

 const minValue = (input) => {
      if(input < 0){
       alert('input has to be greater than 0')
      }else{
        return input;
      }
    }    


 <Form className  = "workout-form">
    <div className ="form-row">
              <label className ="form__label">Distance</label>
              <input type = 'number' value = {distance}  min = '0' onChange = {(e) => setDistance(minValue(e.target.value))} className ="form__input form__input--distance" placeholder="mi"  autoFocus required/>
            </div>
     <button className ="form-btn" onClick = {submitWorkout}>Add Workout</button>
    </Form>

CodePudding user response:

If this code works for checking for negative values you should be able to change if (input < 0) to if ((input < 0) || (input != ""))

CodePudding user response:

const handleChange = e => {
    const value = parseInt(e.target.value);
  if(!isNaN(value) && value > 1){
    setDistance(value)
  }
}
onChange={handleChange}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related