'How can I validate this textfield where it would not allow submission if the entered value is negative?

I have this text field type number, I want to set a minimum of 0 and a text field that does not accept negative values. I was able to do that, however, once I type on it, I would not be able to delete the 0, I would first need to go at front of the 0 then type in a number, and only then would the 0 be deleted. What can I do to fix or are there more suitable ways to do this?

Codesandbox: https://codesandbox.io/s/textfield-7sfdph?file=/demo.js:127-882

Codes:

export default function BasicTextFields() {
  const [fee, setFee] = useState(0);
  const amount = parseInt(1000);
  const total = Number(amount) + Number(fee);
  const handleSubmit = async (e) => {
    e.preventDefault();
    console.log(" submit");
  };
  return (
    <form onSubmit={{ handleSubmit }}>
      <TextField
        label="Fee"
        type="number"
        value={fee}
        onChange={(e) => {
          if (e.target.value === "") {
            setFee(0);
          } else {
            setFee(parseInt(e.target.value));
          }
        }}
        InputProps={{
          inputProps: {
            min: 0
          }
        }}
      />
      <button type="submit">Submit</button>
      <br />
      Total: {total}
    </form>
  );
}


Solution 1:[1]

Your onChange function is setting the value to 0 whenever the value is an empty string. When you delete something you are effectively changing the value, so the onChange function will be called.

Personally I would just call setFee with whatever value they typed because the type=number will already prevent users from typing anything that is not a number and will allow them to clear the field.

You can handle the case for when the value is empty with validation or on the onSubmit function. This is probably a better user experience.

Solution 2:[2]

You can check if number is negative if yes then set value to 0

const total = Number(amount) + (fee ? Number(fee) : 0);
// code 
if (Number(e.target.value) < 0) {
  setFee(0);
} else {
  setFee(parseInt(e.target.value));
}

then on submit check if value is not undefined

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 joaomlap
Solution 2